我已经滚动浏览了vercel文档,但找不到任何可以在Vercel.json
的builds
或functions
部分中指定Python版本的引用.
- 在"构建"中,您指定nPM包
@vercel/python
.我想这更像是node.js
运行python3脚本的界面.
- 在"functions"中,您可以指定无服务器函数.我不确定这是否是您需要的.
参考编号 : https://vercel.com/docs/projects/project-configuration
Solution:
然而,正如Vercel文档中列出的那样,Python版本可以定义为Pipfile
.
参考编号 : https://vercel.com/docs/functions/runtimes/python
注意,Vercel仅支持pony 3.12(默认)和pony 3.9(需要遗留图像,即使用Node.js 16或18.)
Vercel Manuals:
This links might be useful for setting up your first python project on vercel:
https://github.com/vercel/examples/tree/main/python/hello-world
https://github.com/vercel/examples/tree/main/python/flask3
https://github.com/vercel/examples/tree/main/python
What worked for me
首先创建您的http handler
或flottle app
或其他:
## my_app.py
from http.server import BaseHTTPRequestHandler, HTTPServer
import sys
class GETHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/plain')
self.end_headers()
self.wfile.write('Hello, world!\n'.encode('utf-8'))
python_version = f"{sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]}"
self.wfile.write(f'Python version {python_version}'.encode('utf-8'))
# variable required by Vercel
handler = GETHandler
接下来创建一个Pipfile.此bash命令将自动创建Pipfile.
## run in bash
pip install pipenv
pipenv install
自动生成的pipfile看起来应该是这样的:
## Pipfile
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
pipenv = "~=2023.12"
[dev-packages]
[requires]
python_version = "3.9"
接下来创建package.json
.您需要将node.js版本设置为18.x才能在Python 3.9中运行脚本.
## package.json
{
"engines": {
"node": "18.x"
}
}
第三,您需要定义将触发执行Python服务器的路由:
## vercel.json
{
"builds": [
{ "src": "*.py", "use": "@vercel/python" }
],
"redirects": [
{ "source": "/", "destination": "/my_app.py" }
]
}
最后,让我们设置部署设置.在我的项目设置中,我不会添加任何运行或构建命令:
然而,对于python 3.9,请判断您的node.js版本是否为18.x(同一页面,即在部署设置中).
就是这样.部署后,访问生成的路由链接,它会自动将您重定向到/my_app.py
.您可以看到使用python3.9来生成页面: