我的用户模型看起来像这样
class UserModel(Document):
first_name = StringField(required=True, max_length=50)
last_name = StringField(required=True, max_length=50)
username = StringField(required=True)
password = StringField(required=True, min_length=6)
def to_json(self):
return {
"id": str(self.pk),
"first_name": self.first_name,
"last_name": self.last_name,
"username": self.username,
"password": self.password
}
我的身份验证方法如下所示
def authenticate(username, password):
user = UserModel.objects.get(username=username)
if user and checkpw(password.encode('utf-8'), user.password.encode('utf-8')):
return user.to_json()
def identity(payload):
user_id = payload['identity']
u = UserModel.objects.get(pk=user_id)
return u.to_json
jwt = JWT(app, authenticate, identity) # /auth endpoint
我创建了 to_json() 方法希望解决这个问题并序列化将出现在这样的普通查询中的主键
"_id" : ObjectId("5aa9613d4fe35c23fca4d601")
instead of nicely like this~
"id": "5aa9613d4fe35c23fca4d601"
我得到的错误是:
"/home/joe/PyRest/FlaskMongo-venv/lib/python3.6/site-packages/flask_jwt/__init__.py", line 53, in _default_jwt_payload_handler
identity = getattr(identity, 'id') or identity['id']
AttributeError: 'dict' object has no attribute 'id'`