fastapi框架是python的一个新型的框架,号称站在巨人肩膀上的框架。它的最大特点就是既是异步框架又是轻量级框架,它借鉴了一些其他的框架的优点,有着堪比GO语言的性能。本次不介绍fastapi的使用方法,而是分享一下它的部署方法,接下来步入正题。
1.安装模块
本人用的是centos7.9、python3.8
yum install update
pip3 install fastapi
pip3 install uvicorn
pip3 install sqlalchemy
pip3 install uvloop
pip3 install httptools
以上的这些模块全部都有用处,全部安装
2.编写代码
首先创建基本的py文件,也是fastapi的启动文件
#fastapi_start.py
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get('/')
async def Index():
return {"name":"芦苇浮绿水"}
简简单单一个运行程序就写好了,接下来运行
uvicorn fastapi_start:app --reload
运行之后,通过postman访问一下127.0.0.1:8000,输出以下内容
{"name":"芦苇浮绿水"}
3.部署
fastapi的程序写起来是非常方便的,当然部署的方式就不像django那样使用uwsgi做中间服务器了,这里用到gunicorn,它是一个Python WSGI UNIX的HTTP服务器,当然如果你有其他的方式也可不使用这个,没有固定的方式
#下载gunicorn
pip3 install gunicorn
有了这个之后我们大可以使用 gunicorn来启动,网上有很多教程使用以下方式启动的
gunicorn -w 2 -b 127.0.0.1:8000 fastapi_start:app
#实际上这是不可行的,如果直接这样启动,当你访问带有验证模型的接口时就会出现以下错误
'''
Traceback (most recent call last):
File "/usr/local/python3/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 134, in handle
self.handle_request(listener, req, client, addr)
File "/usr/local/python3/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 175, in handle_request
respiter = self.wsgi(environ, resp.start_response)
TypeError: __call__() missing 1 required positional argument: 'send'
'''
会告诉你缺少一个参数(之前我就是这样,废了半天劲)
使用以下方式启动!!!
gunicorn fastapi_start:app -b 0.0.0.0:8000 -w 4 -k uvicorn.workers.UvicornWorker
'''
此处的uvicorn.workers.UvicornWorker需要两个组件用来支撑
uvloop
httptools
所以一开始的包我们就选择安装它
-b 绑定的地址
-w 使用的工作数量
-d 代表守护程序(默认后台运行)
-c 指定配置文件
'''
简单的使用gunicorn启动过之后在postman中测试,正常输出内容
4.配置文件启动
如果我们指定的参数较多,上面的启动方法就会显得非常的繁琐,这时最好的方法就是用配置文件来启动项目
在你项目的根目录下创建gunicorn.py,用作配置文件,名字不是固定的,随便起
debug = True
daemon = True
bind = '0.0.0.0:8000' # 绑定ip和端口号
backlog = 512 # 监听队列
#chdir = '/data/fastest' # gunicorn程序的目录,如果设置环境变量了就不必开启
timeout = 30 # 超时
# worker_class = 'gevent' #使用gevent模式,还可以使用sync 模式,默认的是sync模式
work_class = 'uvicorn.workers.UvicornWorker'
workers = multiprocessing.cpu_count() * 2 + 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"' # 设置gunicorn访问日志格式,错误日志无法设置
"""
其每个选项的含义如下:
h 远程地址
l '-'
u 当前为“-”,或者版本中的用户名
t 请求日期
r 状态栏 (e.g. ``GET / HTTP/1.1``)
s 状态
b 响应长度 或 '-'
f referer
a user agent
T 请求时间(秒)
D 请求时间(微秒)
L 请求时间(十进制秒)
p 进程ID
"""
# 如果使用service启动,这里的pid路径应与service的pid路径保持一致,否则无法启动
pidfile = "/home/fastapi/fastapi_start.pid"
accesslog = "/var/log/gunicorn_access.log" # 访问日志文件
errorlog = "/var/log/gunicorn_error.log" # 错误日志文件
#gunicorn.py
# Gunicorn的配置可以参考:
# https://blog.csdn.net/y472360651/article/details/78538188
# https://docs.gunicorn.org/en/stable/settings.html#server- mechanics
ok,配置文件已经写好,接下来使用配置文件启动
gunicorn fastapi_start:app -c gunicorn.py -k uvicorn.workers.UvicornWorker
此时配置文件启动完成,postman访问接口,输出内容{“name”:“芦苇浮绿水”}
另外我们也可以使用脚本来启动服务,创建gunicorn_fast.service脚本
[Unit]
Description=Gunicorn fast
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/home/fastapi/fastapi_start.pid
# 这里使用了虚拟环境下的Gunicorn
ExecStart=/usr/bin/gunicorn -c /home/fastapi/gunicorn.py fastapi_start:app
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
systemctl start/stop/restart gunicorn_fast.service
5.配置Nginx
一个服务怎能没有nginx呢,fastapi也不例外,在nginx.cnf中配置
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
access_log /var/log/myweb_access.log;
error_log /var/log/myweb_error.log;
client_max_body_size 300M;
location / {
proxy_pass http://127.0.0.1:8000/;
}
}
重启nginx,配置完成