ex: I want to write a decorator wrap the route handler to carry out some HTTP Basic validation, like:
@require_login
async def user_index(request):
pass
so, if I can get current request context in a request object, it will be very convenient:
from sanic.request import request
def require_login(f):
authorization = request.headers.get("authorization")
# parse authorization header
if authorized:
f(request)
else: return json({'msg': 403})
I don't know how sanic's request context actual implementation, maybe we can simply copy the current coroutine's request context to a global request object, and just cover it when another async handler execute.
You don't need a global object for your decorator. Your decorator can intercept the request and check against it.
def require_login():
def decorator(f):
@wraps(f)
async def decorated_function(request, *args, **kwargs):
# you can check against request here
authorized = False
if authorized:
response = await f(request, *args, **kwargs)
return response
else:
return json({'status': 'not_authorized'}, 403)
return decorated_function
return decorator
@app.route("/")
@require_login()
async def test(request):
return json({"hello": "world"})
@subyraman Thanks !!!!

document is too simple 馃槀 and your can intercept the request can add in document 馃槅
Most helpful comment
You don't need a global object for your decorator. Your decorator can intercept the request and check against it.