2021-11-23 21:00:25 +00:00
|
|
|
from sanic import Blueprint, Sanic
|
2020-05-14 00:54:47 +01:00
|
|
|
from sanic.response import text
|
2021-11-23 21:00:25 +00:00
|
|
|
|
|
|
|
"""
|
|
|
|
Demonstrates that blueprint request middleware are executed in the order they
|
2020-05-14 00:54:47 +01:00
|
|
|
are added. And blueprint response middleware are executed in _reverse_ order.
|
|
|
|
On a valid request, it should print "1 2 3 6 5 4" to terminal
|
2021-11-23 21:00:25 +00:00
|
|
|
"""
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2021-12-23 22:30:27 +00:00
|
|
|
app = Sanic("Example")
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2021-12-23 22:30:27 +00:00
|
|
|
bp = Blueprint("bp_example")
|
2021-11-23 21:00:25 +00:00
|
|
|
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2021-11-23 21:00:25 +00:00
|
|
|
@bp.on_request
|
2020-05-14 00:54:47 +01:00
|
|
|
def request_middleware_1(request):
|
2021-11-23 21:00:25 +00:00
|
|
|
print("1")
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2021-11-23 21:00:25 +00:00
|
|
|
|
|
|
|
@bp.on_request
|
2020-05-14 00:54:47 +01:00
|
|
|
def request_middleware_2(request):
|
2021-11-23 21:00:25 +00:00
|
|
|
print("2")
|
|
|
|
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2021-11-23 21:00:25 +00:00
|
|
|
@bp.on_request
|
2020-05-14 00:54:47 +01:00
|
|
|
def request_middleware_3(request):
|
2021-11-23 21:00:25 +00:00
|
|
|
print("3")
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2021-11-23 21:00:25 +00:00
|
|
|
|
|
|
|
@bp.on_response
|
2020-05-14 00:54:47 +01:00
|
|
|
def resp_middleware_4(request, response):
|
2021-11-23 21:00:25 +00:00
|
|
|
print("4")
|
|
|
|
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2021-11-23 21:00:25 +00:00
|
|
|
@bp.on_response
|
2020-05-14 00:54:47 +01:00
|
|
|
def resp_middleware_5(request, response):
|
2021-11-23 21:00:25 +00:00
|
|
|
print("5")
|
|
|
|
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2021-11-23 21:00:25 +00:00
|
|
|
@bp.on_response
|
2020-05-14 00:54:47 +01:00
|
|
|
def resp_middleware_6(request, response):
|
2021-11-23 21:00:25 +00:00
|
|
|
print("6")
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2021-11-23 21:00:25 +00:00
|
|
|
|
|
|
|
@bp.route("/")
|
2020-05-14 00:54:47 +01:00
|
|
|
def pop_handler(request):
|
2021-11-23 21:00:25 +00:00
|
|
|
return text("hello world")
|
|
|
|
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2021-11-23 21:00:25 +00:00
|
|
|
app.blueprint(bp, url_prefix="/bp")
|
2020-05-14 00:54:47 +01:00
|
|
|
|
2023-07-05 11:45:08 +01:00
|
|
|
if __name__ == "__main__":
|
|
|
|
app.run(host="0.0.0.0", port=8000, debug=True, auto_reload=False)
|