2010-03-20 39 views
3

我正在使用MongoEngine集成MongoDB。它提供了一個標準的pymongo設置缺乏的認證和會話支持。擴展MongoEngine用戶文檔是不好的做法嗎?

在普通的django auth中,擴展User模型被認爲是不好的做法,因爲不能保證它在任何地方都能正確使用。這是mongoengine.django.auth的情況嗎?

如果它被認爲是不好的做法,什麼是最好的方式來附加一個單獨的用戶配置文件? Django有指定AUTH_PROFILE_MODULE的機制。這是否也支持MongoEngine,或者我應該手動進行查找?

回答

2
+2

你能編輯你的答案並添加一個解釋這個鏈接的鏈接嗎?我似乎無法找到任何有關它的信息。 – Soviut 2012-08-23 18:21:40

+0

只需檢查[mongoengine]上的代碼(https://github.com/MongoEngine/mongoengine/blob/master/mongoengine/django/auth.py#L37-130),並與[django]上的代碼(https: //github.com/django/django/blob/master/django/contrib/auth/models.py#L379-407)事實上,你可以自己做這個[this](https://github.com/ruandao/mongoengine_django_contrib_auth /blob/master/models.py#L134-163)**注意:這不是使用緩存** – ruandao 2012-08-24 00:33:02

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 
0

在Django的1.5現在可以使用一個可配置的用戶對象,所以這是一個偉大的理由不使用一個單獨的對象,我認爲它是安全的說如果你使用的是Django < 1.5但是期望在某個時候升級,那麼擴展User模型已不再被認爲是不好的做法。在Django 1.5,可配置的用戶對象被設定爲:

AUTH_USER_MODEL = 'myapp.MyUser' 
在你的settings.py

。如果您正在更改以前的用戶配置,則會有一些更改會影響集合名稱等。如果您尚不想升級到1.5,則可以暫時擴展User對象,然後在您稍後進一步更新它時升級到1.5。

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

注:我沒有在Django 1.5 w/MongoEngine中親自嘗試過,但期望它應該支持它。

+0

沒有這不起作用,因爲'mongoengine.django.auth.User'目前沒有get_profile()方法實現。 – 2012-11-22 13:40:34

相關問題