vercel简介
vercel是一个代码托管平台,它能够托管你的静态html界面,甚至能够托管你的node.js与Python服务端脚本,简直是不想配服务器的懒人的福音!
新建工程
首先,新建一个fastApi项目,我这里用的Pycharm
![使用Vercel托管Python后端API https://cdn.guitang.fun/Blog/image-20240606084906857.png](https://cdn.guitang.fun/Blog/image-20240606084906857.png)
新建完成后已经帮我们自动写好了demo和测试用例,按图中顺序依次执行,验证本地可以正常运行
![使用Vercel托管Python后端API https://cdn.guitang.fun/Blog/image-20240606093818753.png](https://cdn.guitang.fun/Blog/image-20240606093818753.png)
添加vercel配置
要部署到 Vercel,需要一个配置文件,在根目录中创建vercel.json并添加以下Json数据:
{
"builds": [
{"src": "/main.py", "use": "@vercel/python"}
],
"routes": [
{"src": "/(.*)", "dest": "main.py"}
]
}
在继续部署之前,让我们创建一个包含应用程序依赖项的文件:requirements.txt,该文件通过pipreqs库生成,安装方法如下:
pip install pipreqs
pipreqs 指定项目目录, 将项目所依赖组件写入“requirements.txt” 文件
pipreqs ./ --ignore ".venv" --encoding utf8
//requirements.txt
fastapi==0.111.0
同步本地代码到Github
在github上创建该仓库
![使用Vercel托管Python后端API https://cdn.guitang.fun/Blog/image-20240606103310902.png](https://cdn.guitang.fun/Blog/image-20240606103310902.png)
然后将本地代码提交到该仓库
git remote add origin https://github.com/gui66497/ImageChatApi.git
git branch -M main
git push -u origin main
部署到vercel
打开并登录vercel官网,可以看到我们刚才创建的项目了(前提你得确保vercel关联了你的github账号)
![使用Vercel托管Python后端API https://cdn.guitang.fun/Blog/image-20240606103310904.png](https://cdn.guitang.fun/Blog/image-20240606103310904.png)
什么都不用改,直接点Deploy
![使用Vercel托管Python后端API https://cdn.guitang.fun/Blog/image-20240606103342432.png](https://cdn.guitang.fun/Blog/image-20240606103342432.png)
发布成功
![使用Vercel托管Python后端API https://cdn.guitang.fun/Blog/image-20240606103450968.png](https://cdn.guitang.fun/Blog/image-20240606103450968.png)
访问url可以看到正确返回了Json数据,部署到此完成。
![使用Vercel托管Python后端API https://cdn.guitang.fun/Blog/image-20240606103611751.png](https://cdn.guitang.fun/Blog/image-20240606103611751.png)
![使用Vercel托管Python后端API https://cdn.guitang.fun/Blog/image-20240606103625801.png](https://cdn.guitang.fun/Blog/image-20240606103625801.png)
发表回复