使用Flask JWT时出错,AttributeError:'list'对象没有属性'id',并显示500内部服务器错误

时间:2019-03-18 20:10:38

标签: python python-3.x flask jwt flask-jwt

security.py


    from user import User    
    from werkzeug.security import safe_str_cmp

    users =[User(1,'abc','abc')  ]

    username_mapping = {u.username:u for u in users}

    userid_mapping = {u.uid: u for u in users}

    def authenticate(username,password):
        user= username_mapping.get(username,None)
        if user and safe_str_cmp(user.password , password):
            return users

    def identity(payload):
        user_id=payload['identity']
        return userid_mapping.get(user_id,None)


app.py


    from flask import Flask,request  
    from flask_restful import Api,Resource 
    from flask_jwt import JWT, jwt_required  
    from security import authenticate,identity


    app = Flask(__name__)  
    app.security_key='cool'  
    api = Api(app)


    jwt = JWT(app,authenticate,identity) #create new endpoint /auth


上面的JWT函数的

/ auth POST方法显示500内部服务器错误并给出下面的错误日志

Traceback (most recent call last):
  File "/usr/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/lib/python3.7/site-packages/flask_restful/__init__.py", line 273, in error_router
    return original_handler(e)
  File "/usr/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/usr/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/iamabhi67/.local/lib/python3.7/site-packages/flask_jwt/__init__.py", line 125, in _default_auth_request_handler
    access_token = _jwt.jwt_encode_callback(identity)
  File "/home/iamabhi67/.local/lib/python3.7/site-packages/flask_jwt/__init__.py", line 62, in _default_jwt_encode_handler
    payload = _jwt.jwt_payload_callback(identity)
  File "/home/iamabhi67/.local/lib/python3.7/site-packages/flask_jwt/__init__.py", line 53, in _default_jwt_payload_handler
    identity = getattr(identity, 'id') or identity['id']
AttributeError: 'list' object has no attribute 'id'

3 个答案:

答案 0 :(得分:0)

您的authenticate函数返回users,这是一个列表。它应该返回一个用户对象(具有id属性)。签出Quickstart

答案 1 :(得分:0)

userid_mapping = {u.uid: u for u in users}

您正在将dict中的id设置为uid。理解,您的代码可以与{u.id: u for u in users}一起使用(至少在我的机器上)。 JWT在找不到id属性时会发现它抛出该讨厌的异常。

答案 2 :(得分:0)

返回的应该是用户,而不是用户

  def authenticate(username,password):
    user= username_mapping.get(username,None)
    if user and safe_str_cmp(user.password , password):
        return user