开发部署
安装asgi插件
pipenv install uvicorn
# main.py
from fastapi import FastApi
app=FastApi()
@app.get('/hello')
async def hello():
return {'message':'hello World'}
nvicorn main:app --reload 开发模式下运行 热加载
生产环境部署 CentOS8.x +Nginx
安装插件 pipenv install gunicorn
shell中执行gunicorn -v有版本输出表示安装成功
# 编写配置文件 gunicorn.py
daemon=True
bind='0.0.0.0:8000'
pidfile='/var/run/gunicorn.pid'
chdir='/opt/web/fastapi' # 工作目录
worker_class='uvicorn.workers.UvicornWorker'
workers=1 #multiprocessing.cpu_count()+1
threads=2
loglevel='debug' # 日志级别
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'
accesslog = "/opt/web/fastapi/gunicorn_access.log"
errorlog = "/opt/web/fastapi/gunicorn_error.log"
gunicorn main:app -c gunicorn.py
在gunicorn_error.log 文件中看到日志输出表示启动成功
配置 gunicorn.service服务开机自启动
cat >/usr/lib/systemd/system/gunicorn.service << EOF
[Unit]
Description=Gunicorn fast
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/var/run/gunicorn.pid
ExecStart=/root/.local/share/virtualenvs/fastapi-Xq8atoqR/bin/gunicorn -c
/opt/web/fastapi/gunicorn.py main:app
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable gunicorn
systemctl start gunicorn
查看服务状态
systemctl status gunicorn
配置nginx代理访问
server {
listen 80;
server_name api.rainbow.cn;
access_log /var/log/nginx/access.log;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
nginx -s reload
完成FastApi的生产部署