2021-11-23 23:00:25 +02:00
|
|
|
from random import randint
|
|
|
|
|
2019-01-02 14:52:25 +08:00
|
|
|
from sanic import Sanic
|
|
|
|
from sanic.response import text
|
|
|
|
|
2021-11-23 23:00:25 +02:00
|
|
|
|
2021-12-24 00:30:27 +02:00
|
|
|
app = Sanic("Example")
|
2019-01-02 14:52:25 +08:00
|
|
|
|
|
|
|
|
2021-11-23 23:00:25 +02:00
|
|
|
@app.middleware("request")
|
2019-01-02 14:52:25 +08:00
|
|
|
def append_request(request):
|
2021-11-23 23:00:25 +02:00
|
|
|
request.ctx.num = randint(0, 100)
|
2019-01-02 14:52:25 +08:00
|
|
|
|
|
|
|
|
2021-11-23 23:00:25 +02:00
|
|
|
@app.get("/pop")
|
2019-01-02 14:52:25 +08:00
|
|
|
def pop_handler(request):
|
2021-11-23 23:00:25 +02:00
|
|
|
return text(request.ctx.num)
|
2019-01-02 14:52:25 +08:00
|
|
|
|
|
|
|
|
2021-11-23 23:00:25 +02:00
|
|
|
@app.get("/key_exist")
|
2019-01-02 14:52:25 +08:00
|
|
|
def key_exist_handler(request):
|
|
|
|
# Check the key is exist or not
|
2021-11-23 23:00:25 +02:00
|
|
|
if hasattr(request.ctx, "num"):
|
|
|
|
return text("num exist in request")
|
2019-01-02 14:52:25 +08:00
|
|
|
|
2021-12-06 15:17:01 +08:00
|
|
|
return text("num does not exist in request")
|
2019-01-02 14:52:25 +08:00
|
|
|
|
2023-07-05 13:45:08 +03:00
|
|
|
if __name__ == "__main__":
|
|
|
|
app.run(host="0.0.0.0", port=8000, debug=True)
|