一、編寫sanic腳本
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 = 'sanic.worker.GunicornWorker'
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即可。
