How can I add python type annotations to the flask global context g?

前端 未结 3 1285
挽巷
挽巷 2021-01-05 06:07

I have a decorator which adds a user onto the flask global context g:

class User:
    def __init__(self, user_data) -&         


        
3条回答
  •  甜味超标
    2021-01-05 06:46

    You can annotate an attribute on a class, even if that class isn't yours, simply with a colon after it. For example:

    g.user: User
    

    That's it. Since it's presumably valid everywhere, I would put it at the top of your code:

    from functools import wraps
    
    from flask import Flask, g
    
    app = Flask(__name__)
    
    
    class User:
        def __init__(self, user_data) -> None:
            self.username: str = user_data["username"]
            self.email: str = user_data["email"]
    
    
    # Annotate the g.user attribute
    g.user: User
    
    
    def login_required(f):
        @wraps(f)
        def wrap(*args, **kwargs):
            g.user = User({'username': 'wile-e-coyote',
                           'email': 'coyote@localhost'})
    
            return f(*args, **kwargs)
    
        return wrap
    
    
    @app.route('/')
    @login_required
    def hello_world():
        return f'Hello, {g.user.email}'
    
    
    if __name__ == '__main__':
        app.run()
    

    That's it.

提交回复
热议问题