sanic中介軟體和監聽器
阿新 • • 發佈:2018-12-11
from sanic.response import text @app.route("/get_info") async def get_info(request): print(request.url) return text("it is ok!") @app.middleware("request") async def get_request_middleware(request): print("請求中介軟體") @app.middleware("response") async def get_response_middleware(request,response): print("響應中介軟體")
請求中介軟體 http://localhost:5000/get_info 響應中介軟體
二:監聽器
如果需要在伺服器啟動/關閉的時候,執行一些特殊的程式碼,則可以使用以下監聽器:
before_server_start:在伺服器啟動之前執行
after_server_start:在伺服器啟動之後執行
@app.listener("before_server_start") async def before_server_start(request,loop): print("before_server_start") @app.listener("after_server_start") async def after_server_start(request,loop):print("after_server_start") @app.listener("before_server_stop") async def before_server_stop(request,loop): print("before_server_stop") @app.listener("after_server_stop") async def after_server_stop(request,loop): print("after_server_stop")