python - 我在使用 Flask_JWT 和 Mongoengine 时遇到错误 'dict' 对象没有属性 'id'

标签 python flask mongoengine flask-jwt

我的用户模型看起来像这样

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'`

最佳答案

这是 Flask-JWT 的常见投诉。乍一看,它似乎有 7 个开放的合并请求来修复它:https://github.com/mattupstate/flask-jwt/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+id

不幸的是,flask-jwt 已经被废弃很长时间了。也许可以看看flask-jwt-extend或flask-jwt-simple作为仍在积极维护的替代品(IMO设计得更好,但我是作者,所以我当然有偏见);)

关于python - 我在使用 Flask_JWT 和 Mongoengine 时遇到错误 'dict' 对象没有属性 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49414253/

相关文章:

dictionary - Mongoengine - 如何自动更新字典?

python - 如何将 tesseract 添加到我的 Docker 容器中以便我可以使用 pytesseract

python - 将(来回)UNIX 时间戳转换为 pandas.tslib.Timestamp 和系列的日期时间

python - Flask 的通用 CRUD 管理员,带有 WTForms?

python - 使用flask-security确认注册时出错

python - Flask-Sqlalchemy 为 'unique' 整数取非唯一值

Python:自定义JSON解码器的性能

python - 在 Linux Mint 17.3 上安装 python 3.5

python - 通过python mongoengine刷新mongodb集合结构

python - 克隆文档 mongoengine