1 目的
本篇文章介绍如何使用 Vercel 来部署python API 服务。
2 使用方法
2.1 方式一
在/api项目目录中,Vercel将通过文件扩展名自动识别此页面上支持的语言,并将其用作无头服务功能。
文件扩展名:.py
默认版本:Python 3.6
api目录中的Python文件包含从BaseHTTPRequestHandler类继承的处理程序变量或app公开WSGI或ASGI应用程序的变量,将用作无服务器函数。
例如,以下内容将存在api/date.py:
1 2 3 4 5 6 7 8 9 10 11
| from http.server import BaseHTTPRequestHandler from datetime import datetime
class handler(BaseHTTPRequestHandler):
def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')).encode()) return
|
返回当前日期的Python函数示例。
部署后,上面的示例函数将用作无服务器函数,返回当前日期和时间。通过以下链接实时查看:https://python-api.now-examples.vercel.app/api/date
2.2 方式二
部署轻量级的Python Flask API,结构模板如下,只需要在app.py添加各api方法即可:
app.py
1 2 3 4 5 6 7 8
| from flask import Flask, request import requests
app = Flask(__name__)
@app.route('/') def hello_world(): return 'Hello from Flask Github!'
|
requirements.txt
1 2 3 4 5
| Flask==1.1.2 Werkzeug==1.0.0 uvicorn requests pydantic
|
vercel.json
1 2 3 4 5 6 7 8 9
| { "version": 2, "builds": [ { "src": "app.py", "use": "@now/python" } ], "routes": [ { "src": "/(.*)", "dest": "app.py" } ] }
|