Cicada000‘s Xlog

Cicada000‘s Xlog

twitter
telegram
bilibili
github

Write an API deployed on Vercel using Python.

First of all, welcome to visit here to see what I have done, visit here to view JSON data, and visit here to view the project source code.

Cause#

After seeing lz233's OneText Library, I was very interested and wanted to create my own version. Additionally, I wanted to add some new features (such as using GET parameters to retrieve specific types of sentences). However, I wanted to meet two conditions: 1) Do not deploy it on a server. 2) Be able to add and delete sentences and features myself. But I couldn't find the answer I wanted through my research, so I started thinking about creating my own.

Before starting, I knew that Vercel provides the Serverless Functions feature. I thought that only Go projects could use it, so I had the idea of temporarily learning Go. However, after reading the documentation, I found that Python is also supported. This was a pleasant surprise, so I started working on it!

Process#

Actually, the basic tutorials on the internet and the official documentation are quite clear. You can create a file named index.py in the /api directory of the repository and write the following code:

from http.server import BaseHTTPRequestHandler
from cowpy import cow

class handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/plain')
        self.end_headers()
        message = cow.Cowacter().milk('Hello from Python from a Serverless Function!')
        self.wfile.write(message.encode())
        return

And create a requirements.txt file in the same directory to specify the modules and versions needed by Vercel:

cowpy==1.0.3

Then, you can deploy it and see that the official example is successfully displayed:

 _______________________________________________ 
< Hello from Python from a Serverless Function! >
 -----------------------------------------------
     \   ^__^
      \  (oo)\_______
         (__)\       )\/\
           ||----w |
           ||     ||

This was my first encounter with Vercel's Serverless Functions. As I delved deeper, I was even more surprised to find that it can be used with the Flask framework! Knowing this, I became even happier because "building an information system using the Flask framework" is one of the required contents of the information technology course. Although I often slack off in class, I still have some knowledge. Here is an example from Johnson's Memo:

index.py:

from flask import Flask, request
import requests

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello from Flask Github!'

requirements.txt:

Flask==1.1.2
Werkzeug==1.0.0
uvicorn
requests
pydantic

Then, you can see the returned data:

Hello from Flask Github!

With these two examples, I roughly understood the details and completed my own OneText API. You can find the specific usage in the README of the GitHub project.

Interlude#

Writing a program is not as simple as mentioned above. In the process, I encountered many challenges. This small project took me two days to complete. Here are a few points that left a deep impression on me.

1. Importing modules#

Because I needed to retrieve random JSON data and process JSON data, I wrote the following in index.py:

import requests , json , random

At first glance, it seems fine, and indeed it is fine. However, when it comes to requirements.txt, it should be written like this:

requests
pyjson
pyrandom

Yes, some module names are different from their file names, so you must be careful when importing them.

2. Text encoding#

I believe I don't need to emphasize the importance of consistent variable types. However, I want to highlight the issue of text encoding. Characters in variables may encounter encoding issues after being manipulated by various functions (especially for Chinese characters). In my project, I wanted the output to be like this:

{
    "text": "逸一时,误一世,逸久逸久罢矣龄。",
    "by": "田所浩二",
    "from": "《真夏の夜の淫梦》",
    "time": "1919.8.10"
}

But the actual output was like this:

{
    "text": "\u9038\u4e00\u65f6\uff0c\u8bef\u4e00\u4e16\uff0c\u9038\u4e45\u9038\u4e45\u7f62\u77e3\u9f84\u3002",
    "by": "\u7530\u6240\u6d69\u4e8c",
    "from": "\u300a\u771f\u590f\u306e\u591c\u306e\u6deb\u68a6\u300b",
    "time": "1919.8.10"
}

After some exploration and troubleshooting, I found that when using the json.dumps function, the default encoding for outputting Chinese characters is Unicode. However, I wanted it to be output in UTF-8 encoding, so I added ensure_ascii=False to achieve this.

3. Remember to check the logs#

During this experience, one thing that left a deep impression on me was to check the output logs more often. This is extremely useful when troubleshooting and solving errors (although it's partly due to my lack of experience, as it was my first time working on this).

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.