How to Deploy a Python Serverless Function to Vercel | by Mahbub Zaman | Jan, 2021
Here is the link to the repository I’ve created. After you have downloaded the code to your local machine, you can see a python file called
index.py inside api folder. According to Vercel’s documentation for Python, if a Python file has a singular HTTP handler variable, inheriting from the BaseHTTPRequestHandler class handler within the api directory, Vercel will serve it as a serverless function.
Let’s break down the individual ingredients of the
from http.server import BaseHTTPRequestHandler
from urllib import parseclass handler(BaseHTTPRequestHandler): def do_GET(self):
s = self.path
dic = dict(parse.parse_qsl(parse.urlsplit(s).query))
self.end_headers() if "name" in dic:
message = "Hello, " + dic["name"] + "!"
message = "Hello, stranger!" self.wfile.write(message.encode())
For this example, we want to handle the query string. If you look at the documentation, the
path instance variable contains the request path. Now let’s parsed the
path variable into a dictionary for our convenience. Moreover, I’ve set the HTTP status code to 200 and the content type as plain text.
The following line looks for a key called
name in the dictionary. If the key is present, the variable
message will contain
Hello, followed by the
Hello, stranger!. You can read more about advanced Python usage from here. Finally, I’m returning the encoded content of the
message, which is utf-8 by default.
Once you have clicked Continue, you should see the following dialogue.
In my case, I’m going to use my git repository link, which is https://github.com/lifeparticle/vercel-python. Now click Continue and finally click Deploy.
Read More …