sanic/examples/amending_request_object.py

30 lines
585 B
Python
Raw Normal View History

from random import randint
2019-01-02 06:52:25 +00:00
from sanic import Sanic
from sanic.response import text
app = Sanic("Example")
2019-01-02 06:52:25 +00:00
@app.middleware("request")
2019-01-02 06:52:25 +00:00
def append_request(request):
request.ctx.num = randint(0, 100)
2019-01-02 06:52:25 +00:00
@app.get("/pop")
2019-01-02 06:52:25 +00:00
def pop_handler(request):
return text(request.ctx.num)
2019-01-02 06:52:25 +00:00
@app.get("/key_exist")
2019-01-02 06:52:25 +00:00
def key_exist_handler(request):
# Check the key is exist or not
if hasattr(request.ctx, "num"):
return text("num exist in request")
2019-01-02 06:52:25 +00:00
return text("num does not exist in request")
2019-01-02 06:52:25 +00:00
2023-10-25 00:22:00 +01:00
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)