Flask-mongoengine文档标识

时间:2016-04-11 16:43:53

标签: python mongodb flask flask-mongoengine

我试图在我的应用程序中实现flask-login,它也使用了flask-mongoengine。这是我的用户原型:

class User(db.Document, UserMixin):
    username = db.StringField(max_length=80)
    email = db.StringField(max_length=255, unique=True)
    password = db.StringField(max_length=255, required=True)
    active = db.BooleanField(default=True)

    def __init__(self, *args, **kwargs):
        super(db.Document, self).__init__(self)
        try:
            self.username = kwargs['username']
            self.email = kwargs['email']
            self.password = kwargs['password']
        except:
            flash('Bad arguments for User')

    @staticmethod
    def salt_password(password):
        return generate_password_hash(password)

    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return self.active

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self._id)

    def __repr__(self):
        return '<User %r>' % (self.username)

    def check_pwd(self, password):
        return check_password_hash(self.password, password)

但是,当我从登录视图中调用login_user(user)函数时,它会调用get_id的{​​{1}}方法,但User会返回self._id。我也试过None同样的结果。然后,我尝试明确地添加self.id字段:

_id

但是,class User(db.Document, UserMixin): _id = db.ObjectIdField(default=bson.ObjectId()) 给了我self._id而不是用户ID。

如何检索用户的'User u'username'>

2 个答案:

答案 0 :(得分:1)

我找到了解决此问题的方法。我的用户原型使用pymongo更新如下:

def get_id(self):
    user_queried = self._get_collection().find_one({'username':self.username, 'email':self.email, 'password':self.password})
    if user_queried is not None:
        return unicode(user_queried['_id'])
    else:
        return 'None'

答案 1 :(得分:1)

虽然我不知道是否仍然需要您的问题的答案 - 您找到了一个解决方案,您的问题已经过时了。但如果有其他人到来我用以下代码解决了它:

from mongoengine import Document, StringField, FloatField, BooleanField

class User(Document):

name = StringField(primary_key=True, required=True, max_length=50)
mail = StringField(required=True, max_length=255)
password = StringField(required=True, max_length=80)
first_name = StringField(max_length=255)
second_name = StringField(max_length=255)
authenticated = True  # BooleanField(required=True, default=True)
is_active = True  # BooleanField(required=True, default=True)

meta = {'db_alias': 'users'}

@property
def is_authenticated(self):
    return True

@property
def is_active(self):
    return True

@property
def is_anonymous(self):
    return False

def get_id(self):
    return self.name

并添加了以下user_loader

@login_manager.user_loader
def load_user(user_id):
    user = User.objects(name=user_id)[0]
    return user