1、创建app
#main.py from sanic import Sanic from sanic.response import json as JsonResponse,text,html from views.user import user_bp app = Sanic(__name__, strict_slashes = False) #strict_slashes 对URL最后的 / 符号是否严格要求 app.blueprint(user_bp)#注册蓝图 #服务启动运行 @app.listener('before_server_start') async def setup_db(app, loop): pass #服务器关闭之前 @app.listener('before_server_stop') async def close_db(app, loop): pass #异常监听 @app.exception(ExpiredSignatureError) async def handleSignatureError(request, exception): return json() #中间件 @app.middleware('request') async def middleware: pass @app.route("/") def index(request): return JsonResponse({"hello":"world"}) if __name__ == '__main__': app.run(host = "127.0.0.1", port = 80, debug = True)
2、创建蓝图
#views/user.py from sanic import Blueprint from sanic.response import json as JsonResponse from sanic.views import HTTPMethodView user_bp = Blueprint('user', url_prefix = "/user") async def login(request): pass class UserViewsAPI(HTTPMethodView): async def get(self, request): pass async def post(self, request): pass async def put(self, request): pass async def delete(self, request): pass user_bp.add_route(login, "/login", methods = ["POST"]) user_bp.add_route(UserViewsAPI.as_view(), "/<obj_id>")
二、部署到服务器
1、编写gunicorn配置文件
#gunicorn_config.py debug = True loglevel = 'debug' bind = '127.0.0.1:8998' #内部端口 pidfile = 'log/gunicorn.pid' logfile = 'log/debug.log' workers = 指定进程数量 worker_class = 'uvicorn.workers.UvicornWorker'
2、使用supervisor运行gunicorn/uvicorn脚本,参考链接(https://www.cnblogs.com/mrzhao520/p/14139153.html)
#/etc/supervisord.d/projectname.ini
[program:projectname]
directory=项目的路径
command=gunicorn -c gunicorn_config.py main:app #启动gunicorn
autostart=true #是否随supervisor启动
autorestart=true #是否在意外关闭后重启
startretires=3 #尝试启动次数
user=root #指定用户执行
[fcgi-program:uvicorn] socket=tcp://127.0.0.1:8997 command=uvicorn main:app numprocs=3 #supervisor进程数 autostart=true autorestart=true startretries=3 user=root process_name=%(program_name)s_%(process_num)02d #多个进程需要设置不同的名字 stderr_logfile=logs/error.log stdout_logfile=logs/out.log
3、nginx部署
#/usr/local/nginx/conf/nginx.conf
events {
worker_connections 1024; #nginx的并发数
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
server {
listen 80;
server_name 域名;
location / {
proxy_pass http://127.0.0.1:8998; #gunicorn启动的端口
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
最后运行supervisor和nginx即可。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:(gunicorn | uvicorn)+nginx 部署python-sanic项目 - Python技术站