Sanic: Access request context globally

Created on 5 Apr 2018  路  4Comments  路  Source: sanic-org/sanic

Flask allows to access request context instance from anywhere in the code, simply by importing flask.request. An exception is thrown when there is no context (app is starting or request is already finished).

This is no similar context proxy in sanic and it became tricky to get it when outside an handler.
One use case that we got is, being able to get the current request and add more context to the logs (url, method, ... ect) when they are created from within a request context.

One dirty workaround:

    def get_request(limit=20):
        """ sanic does not provide a globally accessible request context
             so we inspect previous frames to get one
        """
        frame = sys._getframe()
        request = None
        while frame and limit > 0:
            f_locals = frame.f_locals
            if 'request' in f_locals:
                f_request = f_locals['request']
                if isinstance(f_request, Request):
                    request = f_request
                    break
            frame = frame.f_back
            limit -= 1
        return request

Most helpful comment

Global variables are crap!

All 4 comments

Global variables are crap!

Duplicate of #69

I'm thinking the global request context is sort of anti-pattern. and also it's thread-local variable in Flask i guess. Sanic is async framework, which is single thread per process, if we really wanna achieve this, we have to utilize sth. like https://github.com/Skyscanner/aiotask-context.
But i don't think it's a good design to have global request context.

Agreed on the global variables crapiness ;)
I just didn't knew of alternatives, will look into aiotask-context, that may be the solution I need.

Closing this issue since its indeed a duplicate 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

graingert picture graingert  路  3Comments

davidtgq picture davidtgq  路  3Comments

eseglem picture eseglem  路  4Comments

ZeeRoc picture ZeeRoc  路  3Comments

sirex picture sirex  路  4Comments