Why does Flask g (global) not work with Flask-RESTX?

69 Views Asked by At

Adding swagger to my application, I decided to use Flask-RESTX. I also have a security_check that must be executed before each request,

@app.before_request
def security_check():
    user_uuid = request.headers.get("UserUuid", None)
    user: = get_user_by_userUuid_service(user_uuid)
    g.user = user
    return user

I have decorators.py to verify authorized users. I can't use the built-in login_user() and don't want to

def has_authorize_user(func):
    @functools.wraps(func)
    def decorate(*args, **kwargs):
        if g.user is not None:
            response = func(*args, **kwargs)
            return response
        else:
            return Response("User is unauthorized", status=401)

    return decorate

def transactional(func):
    def wrapped(*args, **kwargs):
        with app.app_context():
            response = func(*args, **kwargs)
            
    return wrapped

routes.py

api.add_resource(CloseController, f"/api", methods=['GET', 'POST'], endpoint='close-controller')

controller.py

class CloseController(Resource):
    def get(self):
        response = get_close_service()
        return response

service.py

@transactional
def get_close_service():
    # g.user == None
    ...

The problem is that when requesting to http://127.0.0.1/api, not possible to get g.user inside CloseController.

What are the ways to solve this problem and How works global variables in Flask g together with Flask-RESTX? ?

I was looking for a similar before_request method in Flask-REST, but I couldn't find anything.

1

There are 1 best solutions below

0
On

I came to decision that for http requests, transactional works without with app.app_context(), instead i did with Session(engine_)

For non-http requests, i pass user to function (for example in headers).

You can also use session['user'] = user for communication between functions