扩展MongoEngine用户文档是坏习惯吗?

3 投票
3 回答
1885 浏览
提问于 2025-04-15 20:37

我正在使用MongoEngine来整合MongoDB。这个工具提供了认证和会话支持,而普通的pymongo设置是没有这些功能的。

在普通的Django认证中,扩展用户模型被认为是不好的做法,因为没有保证它会在所有地方都被正确使用。那么在mongoengine.django.auth中也是这样吗?

如果确实被认为是不好的做法,那么有什么好的方法来附加一个单独的用户资料呢?Django有机制可以指定AUTH_PROFILE_MODULE。在MongoEngine中也支持这个吗,还是说我需要手动去查找?

3 个回答

0

在Django 1.5版本中,你可以使用一个可配置的用户对象,这就是不再使用单独对象的一个好理由。我觉得可以说,如果你使用的是Django 1.5之前的版本,并且打算在某个时候升级,那么扩展用户模型已经不再被视为坏习惯了。在Django 1.5中,设置可配置用户对象的方法是:

AUTH_USER_MODEL = 'myapp.MyUser'

在你的settings.py文件中。如果你是从之前的用户配置切换过来的,那么会有一些变化,比如集合命名等。如果你现在还不想升级到1.5,可以先扩展用户对象,等到你真的升级到1.5时再进一步更新。

https://docs.djangoproject.com/en/dev/topics/auth/#auth-custom-user

注意:我个人还没有在Django 1.5和MongoEngine中尝试过这个,但我预计它应该是支持的。

4

我们刚刚扩展了用户类。

class User(MongoEngineUser):
    def __eq__(self, other):
        if type(other) is User:
            return other.id == self.id
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def create_profile(self, *args, **kwargs):
        profile = Profile(user=self, *args, **kwargs)
        return profile

    def get_profile(self):
        try:
            profile = Profile.objects.get(user=self)
        except DoesNotExist:
            profile = Profile(user=self)
            profile.save()
        return profile

    def get_str_id(self):
        return str(self.id)

    @classmethod
    def create_user(cls, username, password, email=None):
        """Create (and save) a new user with the given username, password and
email address.
"""
        now = datetime.datetime.now()

        # Normalize the address by lowercasing the domain part of the email
        # address.
        # Not sure why we'r allowing null email when its not allowed in django
        if email is not None:
            try:
                email_name, domain_part = email.strip().split('@', 1)
            except ValueError:
                pass
            else:
                email = '@'.join([email_name, domain_part.lower()])

        user = User(username=username, email=email, date_joined=now)
        user.set_password(password)
        user.save()
        return user
2

MongoEngine 现在支持 AUTH_PROFILE_MODULE 这个功能。

你可以在这里查看相关代码:https://github.com/ruandao/mongoengine_django_contrib_auth/blob/master/models.py#L134-163

撰写回答