Sanic: can sanic realize a global proxy for request object ?

Created on 16 Feb 2017  路  2Comments  路  Source: sanic-org/sanic

can sanic realize a global proxy for request object ?

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.

Most helpful comment

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"})

All 2 comments

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 !!!!

screen shot 2017-02-17 at 02 01 09

document is too simple 馃槀 and your can intercept the request can add in document 馃槅

Was this page helpful?
0 / 5 - 0 ratings