diff options
Diffstat (limited to 'django/models')
| -rw-r--r-- | django/models/__init__.py | 95 | ||||
| -rw-r--r-- | django/models/auth.py | 219 | ||||
| -rw-r--r-- | django/models/core.py | 121 |
3 files changed, 0 insertions, 435 deletions
diff --git a/django/models/__init__.py b/django/models/__init__.py deleted file mode 100644 index ea0c66f2ae..0000000000 --- a/django/models/__init__.py +++ /dev/null @@ -1,95 +0,0 @@ -from django.core import meta -from django.utils.functional import curry - -__all__ = ['auth', 'core'] - -# Alter this package's __path__ variable so that calling code can import models -# from "django.models" even though the model code doesn't physically live -# within django.models. -for mod in meta.get_installed_models(): - __path__.extend(mod.__path__) - -# First, import all models so the metaclasses run. -modules = meta.get_installed_model_modules(__all__) - -# Now, create the extra methods that we couldn't create earlier because -# relationships hadn't been known until now. -for mod in modules: - for klass in mod._MODELS: - - # Add "get_thingie", "get_thingie_count" and "get_thingie_list" methods - # for all related objects. - for related in klass._meta.get_all_related_objects(): - # Determine whether this related object is in another app. - # If it's in another app, the method names will have the app - # label prepended, and the add_BLAH() method will not be - # generated. - rel_mod = related.opts.get_model_module() - rel_obj_name = related.get_method_name_part() - if isinstance(related.field.rel, meta.OneToOneRel): - # Add "get_thingie" methods for one-to-one related objects. - # EXAMPLE: Place.get_restaurants_restaurant() - func = curry(meta.method_get_related, 'get_object', rel_mod, related.field) - func.__doc__ = "Returns the associated `%s.%s` object." % (related.opts.app_label, related.opts.module_name) - setattr(klass, 'get_%s' % rel_obj_name, func) - elif isinstance(related.field.rel, meta.ManyToOneRel): - # Add "get_thingie" methods for many-to-one related objects. - # EXAMPLE: Poll.get_choice() - func = curry(meta.method_get_related, 'get_object', rel_mod, related.field) - func.__doc__ = "Returns the associated `%s.%s` object matching the given criteria." % \ - (related.opts.app_label, related.opts.module_name) - setattr(klass, 'get_%s' % rel_obj_name, func) - # Add "get_thingie_count" methods for many-to-one related objects. - # EXAMPLE: Poll.get_choice_count() - func = curry(meta.method_get_related, 'get_count', rel_mod, related.field) - func.__doc__ = "Returns the number of associated `%s.%s` objects." % \ - (related.opts.app_label, related.opts.module_name) - setattr(klass, 'get_%s_count' % rel_obj_name, func) - # Add "get_thingie_list" methods for many-to-one related objects. - # EXAMPLE: Poll.get_choice_list() - func = curry(meta.method_get_related, 'get_list', rel_mod, related.field) - func.__doc__ = "Returns a list of associated `%s.%s` objects." % \ - (related.opts.app_label, related.opts.module_name) - setattr(klass, 'get_%s_list' % rel_obj_name, func) - # Add "add_thingie" methods for many-to-one related objects, - # but only for related objects that are in the same app. - # EXAMPLE: Poll.add_choice() - if related.opts.app_label == klass._meta.app_label: - func = curry(meta.method_add_related, related.opts, rel_mod, related.field) - func.alters_data = True - setattr(klass, 'add_%s' % rel_obj_name, func) - del func - del rel_obj_name, rel_mod, related # clean up - - # Do the same for all related many-to-many objects. - for related in klass._meta.get_all_related_many_to_many_objects(): - rel_mod = related.opts.get_model_module() - rel_obj_name = related.get_method_name_part() - setattr(klass, 'get_%s' % rel_obj_name, curry(meta.method_get_related_many_to_many, 'get_object', klass._meta, rel_mod, related.field)) - setattr(klass, 'get_%s_count' % rel_obj_name, curry(meta.method_get_related_many_to_many, 'get_count', klass._meta, rel_mod, related.field)) - setattr(klass, 'get_%s_list' % rel_obj_name, curry(meta.method_get_related_many_to_many, 'get_list', klass._meta, rel_mod, related.field)) - if related.opts.app_label == klass._meta.app_label: - func = curry(meta.method_set_related_many_to_many, related.opts, related.field) - func.alters_data = True - setattr(klass, 'set_%s' % related.opts.module_name, func) - del func - del rel_obj_name, rel_mod, related # clean up - - # Add "set_thingie_order" and "get_thingie_order" methods for objects - # that are ordered with respect to this. - for obj in klass._meta.get_ordered_objects(): - func = curry(meta.method_set_order, obj) - func.__doc__ = "Sets the order of associated `%s.%s` objects to the given ID list." % (obj.app_label, obj.module_name) - func.alters_data = True - setattr(klass, 'set_%s_order' % obj.object_name.lower(), func) - - func = curry(meta.method_get_order, obj) - func.__doc__ = "Returns the order of associated `%s.%s` objects as a list of IDs." % (obj.app_label, obj.module_name) - setattr(klass, 'get_%s_order' % obj.object_name.lower(), func) - del func, obj # clean up - del klass # clean up - del mod -del modules - -# Expose get_app and get_module. -from django.core.meta import get_app, get_module diff --git a/django/models/auth.py b/django/models/auth.py deleted file mode 100644 index 2595727ad0..0000000000 --- a/django/models/auth.py +++ /dev/null @@ -1,219 +0,0 @@ -from django.core import meta, validators -from django.models import core -from django.utils.translation import gettext_lazy as _ - -class Permission(meta.Model): - name = meta.CharField(_('name'), maxlength=50) - package = meta.ForeignKey(core.Package, db_column='package') - codename = meta.CharField(_('codename'), maxlength=100) - class META: - verbose_name = _('Permission') - verbose_name_plural = _('Permissions') - unique_together = (('package', 'codename'),) - ordering = ('package', 'codename') - - def __repr__(self): - return "%s | %s" % (self.package_id, self.name) - -class Group(meta.Model): - name = meta.CharField(_('name'), maxlength=80, unique=True) - permissions = meta.ManyToManyField(Permission, blank=True, filter_interface=meta.HORIZONTAL) - class META: - verbose_name = _('Group') - verbose_name_plural = _('Groups') - ordering = ('name',) - admin = meta.Admin( - search_fields = ('name',), - ) - - def __repr__(self): - return self.name - -class User(meta.Model): - username = meta.CharField(_('username'), maxlength=30, unique=True, validator_list=[validators.isAlphaNumeric]) - first_name = meta.CharField(_('first name'), maxlength=30, blank=True) - last_name = meta.CharField(_('last name'), maxlength=30, blank=True) - email = meta.EmailField(_('e-mail address'), blank=True) - password = meta.CharField(_('password'), maxlength=128, help_text=_("Use '[algo]$[salt]$[hexdigest]'")) - is_staff = meta.BooleanField(_('staff status'), help_text=_("Designates whether the user can log into this admin site.")) - is_active = meta.BooleanField(_('active'), default=True) - is_superuser = meta.BooleanField(_('superuser status')) - last_login = meta.DateTimeField(_('last login'), default=meta.LazyDate()) - date_joined = meta.DateTimeField(_('date joined'), default=meta.LazyDate()) - groups = meta.ManyToManyField(Group, blank=True, - help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in.")) - user_permissions = meta.ManyToManyField(Permission, blank=True, filter_interface=meta.HORIZONTAL) - class META: - verbose_name = _('User') - verbose_name_plural = _('Users') - module_constants = { - 'SESSION_KEY': '_auth_user_id', - } - ordering = ('username',) - exceptions = ('SiteProfileNotAvailable',) - admin = meta.Admin( - fields = ( - (None, {'fields': ('username', 'password')}), - (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), - (_('Permissions'), {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}), - (_('Important dates'), {'fields': ('last_login', 'date_joined')}), - (_('Groups'), {'fields': ('groups',)}), - ), - list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff'), - list_filter = ('is_staff', 'is_superuser'), - search_fields = ('username', 'first_name', 'last_name', 'email'), - ) - - def __repr__(self): - return self.username - - def get_absolute_url(self): - return "/users/%s/" % self.username - - def is_anonymous(self): - return False - - def get_full_name(self): - full_name = '%s %s' % (self.first_name, self.last_name) - return full_name.strip() - - def set_password(self, raw_password): - import sha, random - algo = 'sha1' - salt = sha.new(str(random.random())).hexdigest()[:5] - hsh = sha.new(salt+raw_password).hexdigest() - self.password = '%s$%s$%s' % (algo, salt, hsh) - - def check_password(self, raw_password): - """ - Returns a boolean of whether the raw_password was correct. Handles - encryption formats behind the scenes. - """ - # Backwards-compatibility check. Older passwords won't include the - # algorithm or salt. - if '$' not in self.password: - import md5 - is_correct = (self.password == md5.new(raw_password).hexdigest()) - if is_correct: - # Convert the password to the new, more secure format. - self.set_password(raw_password) - self.save() - return is_correct - algo, salt, hsh = self.password.split('$') - if algo == 'md5': - import md5 - return hsh == md5.new(salt+raw_password).hexdigest() - elif algo == 'sha1': - import sha - return hsh == sha.new(salt+raw_password).hexdigest() - raise ValueError, "Got unknown password algorithm type in password." - - def get_group_permissions(self): - "Returns a list of permission strings that this user has through his/her groups." - if not hasattr(self, '_group_perm_cache'): - import sets - cursor = db.cursor() - # The SQL below works out to the following, after DB quoting: - # cursor.execute(""" - # SELECT p.package, p.codename - # FROM auth_permissions p, auth_groups_permissions gp, auth_users_groups ug - # WHERE p.id = gp.permission_id - # AND gp.group_id = ug.group_id - # AND ug.user_id = %s""", [self.id]) - sql = """ - SELECT p.%s, p.%s - FROM %s p, %s gp, %s ug - WHERE p.%s = gp.%s - AND gp.%s = ug.%s - AND ug.%s = %%s""" % ( - db.quote_name('package'), db.quote_name('codename'), - db.quote_name('auth_permissions'), db.quote_name('auth_groups_permissions'), - db.quote_name('auth_users_groups'), db.quote_name('id'), - db.quote_name('permission_id'), db.quote_name('group_id'), - db.quote_name('group_id'), db.quote_name('user_id')) - cursor.execute(sql, [self.id]) - self._group_perm_cache = sets.Set(["%s.%s" % (row[0], row[1]) for row in cursor.fetchall()]) - return self._group_perm_cache - - def get_all_permissions(self): - if not hasattr(self, '_perm_cache'): - import sets - self._perm_cache = sets.Set(["%s.%s" % (p.package_id, p.codename) for p in self.get_permission_list()]) - self._perm_cache.update(self.get_group_permissions()) - return self._perm_cache - - def has_perm(self, perm): - "Returns True if the user has the specified permission." - if not self.is_active: - return False - if self.is_superuser: - return True - return perm in self.get_all_permissions() - - def has_perms(self, perm_list): - "Returns True if the user has each of the specified permissions." - for perm in perm_list: - if not self.has_perm(perm): - return False - return True - - def has_module_perms(self, package_name): - "Returns True if the user has any permissions in the given package." - if self.is_superuser: - return True - return bool(len([p for p in self.get_all_permissions() if p[:p.index('.')] == package_name])) - - def get_and_delete_messages(self): - messages = [] - for m in self.get_message_list(): - messages.append(m.message) - m.delete() - return messages - - def email_user(self, subject, message, from_email=None): - "Sends an e-mail to this User." - from django.core.mail import send_mail - send_mail(subject, message, from_email, [self.email]) - - def get_profile(self): - """ - Returns site-specific profile for this user. Raises - SiteProfileNotAvailable if this site does not allow profiles. - """ - if not hasattr(self, '_profile_cache'): - from django.conf.settings import AUTH_PROFILE_MODULE - if not AUTH_PROFILE_MODULE: - raise SiteProfileNotAvailable - try: - app, mod = AUTH_PROFILE_MODULE.split('.') - module = __import__('ellington.%s.apps.%s' % (app, mod), [], [], ['']) - self._profile_cache = module.get_object(user_id=self.id) - except ImportError: - try: - module = __import__('django.models.%s' % AUTH_PROFILE_MODULE, [], [], ['']) - self._profile_cache = module.get_object(user__id__exact=self.id) - except ImportError: - raise SiteProfileNotAvailable - return self._profile_cache - - def _module_create_user(username, email, password): - "Creates and saves a User with the given username, e-mail and password." - now = datetime.datetime.now() - user = User(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now) - user.set_password(password) - user.save() - return user - - def _module_make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'): - "Generates a random password with the given length and given allowed_chars" - # Note that default value of allowed_chars does not have "I" or letters - # that look like it -- just to avoid confusion. - from random import choice - return ''.join([choice(allowed_chars) for i in range(length)]) - -class Message(meta.Model): - user = meta.ForeignKey(User) - message = meta.TextField(_('Message')) - - def __repr__(self): - return self.message diff --git a/django/models/core.py b/django/models/core.py deleted file mode 100644 index f78f23f265..0000000000 --- a/django/models/core.py +++ /dev/null @@ -1,121 +0,0 @@ -import base64, md5, random, sys -import cPickle as pickle -from django.core import meta -from django.utils.translation import gettext_lazy as _ - -class Site(meta.Model): - domain = meta.CharField(_('domain name'), maxlength=100) - name = meta.CharField(_('display name'), maxlength=50) - class META: - verbose_name = _('site') - verbose_name_plural = _('sites') - db_table = 'sites' - ordering = ('domain',) - admin = meta.Admin( - list_display = ('domain', 'name'), - search_fields = ('domain', 'name'), - ) - - def __repr__(self): - return self.domain - - def _module_get_current(): - "Returns the current site, according to the SITE_ID constant." - from django.conf.settings import SITE_ID - return get_object(pk=SITE_ID) - -class Package(meta.Model): - label = meta.CharField(_('label'), maxlength=20, primary_key=True) - name = meta.CharField(_('name'), maxlength=30, unique=True) - class META: - verbose_name = _('package') - verbose_name_plural = _('packages') - db_table = 'packages' - ordering = ('name',) - - def __repr__(self): - return self.name - -class ContentType(meta.Model): - name = meta.CharField(_('name'), maxlength=100) - package = meta.ForeignKey(Package, db_column='package') - python_module_name = meta.CharField(_('python module name'), maxlength=50) - class META: - verbose_name = _('content type') - verbose_name_plural = _('content types') - db_table = 'content_types' - ordering = ('package', 'name') - unique_together = (('package', 'python_module_name'),) - - def __repr__(self): - return "%s | %s" % (self.package_id, self.name) - - def get_model_module(self): - "Returns the Python model module for accessing this type of content." - return __import__('django.models.%s.%s' % (self.package_id, self.python_module_name), '', '', ['']) - - def get_object_for_this_type(self, **kwargs): - """ - Returns an object of this type for the keyword arguments given. - Basically, this is a proxy around this object_type's get_object() model - method. The ObjectNotExist exception, if thrown, will not be caught, - so code that calls this method should catch it. - """ - return self.get_model_module().get_object(**kwargs) - -class Session(meta.Model): - session_key = meta.CharField(_('session key'), maxlength=40, primary_key=True) - session_data = meta.TextField(_('session data')) - expire_date = meta.DateTimeField(_('expire date')) - class META: - verbose_name = _('session') - verbose_name_plural = _('sessions') - module_constants = { - 'base64': base64, - 'md5': md5, - 'pickle': pickle, - 'random': random, - 'sys': sys, - } - - def get_decoded(self): - from django.conf.settings import SECRET_KEY - encoded_data = base64.decodestring(self.session_data) - pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] - if md5.new(pickled + SECRET_KEY).hexdigest() != tamper_check: - from django.core.exceptions import SuspiciousOperation - raise SuspiciousOperation, "User tampered with session cookie." - try: - return pickle.loads(pickled) - # Unpickling can cause a variety of exceptions. If something happens, - # just return an empty dictionary (an empty session). - except: - return {} - - def _module_encode(session_dict): - "Returns the given session dictionary pickled and encoded as a string." - from django.conf.settings import SECRET_KEY - pickled = pickle.dumps(session_dict) - pickled_md5 = md5.new(pickled + SECRET_KEY).hexdigest() - return base64.encodestring(pickled + pickled_md5) - - def _module_get_new_session_key(): - "Returns session key that isn't being used." - from django.conf.settings import SECRET_KEY - # The random module is seeded when this Apache child is created. - # Use person_id and SECRET_KEY as added salt. - while 1: - session_key = md5.new(str(random.randint(0, sys.maxint - 1)) + str(random.randint(0, sys.maxint - 1)) + SECRET_KEY).hexdigest() - try: - get_object(session_key__exact=session_key) - except SessionDoesNotExist: - break - return session_key - - def _module_save(session_key, session_dict, expire_date): - s = Session(session_key, encode(session_dict), expire_date) - if session_dict: - s.save() - else: - s.delete() # Clear sessions with no data. - return s |
