sanic/examples/amending_request_object.py

30 lines
554 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(__name__)
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 reqeust")
2019-01-02 06:52:25 +00:00
app.run(host="0.0.0.0", port=8000, debug=True)