Python
30 Nov 2009
 

models.py: "User" class monkeypatching with signals for MongoDB profiles

 
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from django.db import models
from django.contrib.auth.models import User
import pymongo
mongo = pymongo.Connection()
profiles = mongo['gnusmus']['user.profiles']
profiles.ensure_index('email', unique=True)
scheme = mongo['gnusmus']['user.profiles.scheme']
scheme.ensure_index('title', unique=True)
class UserExtension(object):
def _get_profile(self):
doc = profiles.find_one({'email': self.email})
if doc is None: # not found, init
self.profile = {}
return {}
return doc['profile']
def _set_profile(self, doc):
profiles.update({'email': self.email},
{'email': self.email, 'profile': doc},
True) # upsert profile data
profile = property(_get_profile, _set_profile)
def hack_user(sender, *args, **kwargs):
if UserExtension not in sender.__bases__:
sender.__bases__ += (UserExtension,)
models.signals.pre_init.connect(hack_user, sender=User, dispatch_uid="moprofile_user_patch")