Skip to main content
 首页 » 编程设计

Python eve之如何在成功验证后获取当前用户

2025年05月04日14freeliver54

我创建了一个像下面这样的授权 token 类,我使用 self.set_request_auth_value(user['_id']) 来设置这个请求的用户,在一些我想访问这个的钩子(Hook)中用户,我怎样才能得到它?

我尝试了 app.get_request_auth_value(),但事实并非如此。

token 授权类:

class TokenAuth(TokenAuth): 
    def check_auth(self, token, allowed_roles, resource, method): 
        """ Token authentication using itsdangerous """ 
        # TODO: revoked access can be checked here 
        # without even parsing the token 
        s = Serilizer(app.config['SECRET_KEY']) 
        try: 
            data = s.loads(token) 
        except SignatureExpired: 
            return [] 
        except BadSignature: 
            return [] 
        # Celery borker Async task test 
        r = add.delay(4, 4) 
        print r.id 
        # use Eve's own db driver; no additional connections/resources are used 
        users = app.data.driver.db['users'] 
        user = users.find_one({'_id': ObjectId(data.get('id'))}) 
        # Set the user of this request 
        self.set_request_auth_value(user['_id']) 
        return user 

请您参考如下方法:

实际的 auth_value 存储在 Flask 的 g 对象 ( docs ) 中,作为 auth_value。所以在你的回调中你可能会做类似的事情:

import flask 
 
user = flask.g.get('auth_value', None) 
# or, alternatively: 
user = getattr(flask.g, 'auth_value', None) 

或者,为了保持 Eve 语义,您可以使用 current_app:

from flask import current_app 
 
current_app.auth.get_request_auth_value()