-import datetime\r
-import hashlib\r
-from urllib import quote_plus, urlencode\r
-from django.db import models, IntegrityError, connection, transaction\r
-from django.utils.http import urlquote as django_urlquote\r
-from django.utils.html import strip_tags\r
-from django.core.urlresolvers import reverse\r
-from django.contrib.auth.models import User\r
-from django.contrib.contenttypes import generic\r
-from django.contrib.contenttypes.models import ContentType\r
-from django.template.defaultfilters import slugify\r
-from django.db.models.signals import post_delete, post_save, pre_save\r
-from django.utils.translation import ugettext as _\r
-from django.utils.safestring import mark_safe\r
-from django.contrib.sitemaps import ping_google\r
-import django.dispatch\r
-from django.conf import settings\r
-import logging\r
-\r
-if settings.USE_SPHINX_SEARCH == True:\r
- from djangosphinx.models import SphinxSearch\r
-\r
-from forum.const import *\r
-\r
-class MetaContent(models.Model):\r
- """\r
- Base class for Vote, Comment and FlaggedItem\r
- """\r
- content_type = models.ForeignKey(ContentType)\r
- object_id = models.PositiveIntegerField()\r
- content_object = generic.GenericForeignKey('content_type', 'object_id')\r
- user = models.ForeignKey(User, related_name='%(class)ss')\r
-\r
- class Meta:\r
- abstract = True\r
- app_label = 'forum'\r
-\r
-\r
-class DeletableContent(models.Model):\r
- deleted = models.BooleanField(default=False)\r
- deleted_at = models.DateTimeField(null=True, blank=True)\r
- deleted_by = models.ForeignKey(User, null=True, blank=True, related_name='deleted_%(class)ss')\r
-\r
- class Meta:\r
- abstract = True\r
- app_label = 'forum'\r
-\r
-\r
-class ContentRevision(models.Model):\r
- """\r
- Base class for QuestionRevision and AnswerRevision\r
- """\r
- revision = models.PositiveIntegerField()\r
- author = models.ForeignKey(User, related_name='%(class)ss')\r
- revised_at = models.DateTimeField()\r
- summary = models.CharField(max_length=300, blank=True)\r
- text = models.TextField()\r
-\r
- class Meta:\r
- abstract = True\r
- app_label = 'forum'\r
-\r
-\r
-class AnonymousContent(models.Model):\r
- """\r
- Base class for AnonymousQuestion and AnonymousAnswer\r
- """\r
- session_key = models.CharField(max_length=40) #session id for anonymous questions\r
- wiki = models.BooleanField(default=False)\r
- added_at = models.DateTimeField(default=datetime.datetime.now)\r
- ip_addr = models.IPAddressField(max_length=21) #allow high port numbers\r
- author = models.ForeignKey(User,null=True)\r
- text = models.TextField()\r
- summary = models.CharField(max_length=180)\r
-\r
- class Meta:\r
- abstract = True\r
- app_label = 'forum'\r
-\r
-\r
-from meta import Comment, Vote, FlaggedItem\r
-\r
-class Content(models.Model):\r
- """\r
- Base class for Question and Answer\r
- """\r
- author = models.ForeignKey(User, related_name='%(class)ss')\r
- added_at = models.DateTimeField(default=datetime.datetime.now)\r
-\r
- wiki = models.BooleanField(default=False)\r
- wikified_at = models.DateTimeField(null=True, blank=True)\r
-\r
- locked = models.BooleanField(default=False)\r
- locked_by = models.ForeignKey(User, null=True, blank=True, related_name='locked_%(class)ss')\r
- locked_at = models.DateTimeField(null=True, blank=True)\r
-\r
- score = models.IntegerField(default=0)\r
- vote_up_count = models.IntegerField(default=0)\r
- vote_down_count = models.IntegerField(default=0)\r
-\r
- comment_count = models.PositiveIntegerField(default=0)\r
- offensive_flag_count = models.SmallIntegerField(default=0)\r
-\r
- last_edited_at = models.DateTimeField(null=True, blank=True)\r
- last_edited_by = models.ForeignKey(User, null=True, blank=True, related_name='last_edited_%(class)ss')\r
-\r
- html = models.TextField()\r
- comments = generic.GenericRelation(Comment)\r
- votes = generic.GenericRelation(Vote)\r
- flagged_items = generic.GenericRelation(FlaggedItem)\r
-\r
- class Meta:\r
- abstract = True\r
- app_label = 'forum'\r
-\r
- def save(self,**kwargs):\r
- super(Content,self).save(**kwargs)\r
- try:\r
- ping_google()\r
- except Exception:\r
- logging.debug('problem pinging google did you register you sitemap with google?')\r
-\r
- def get_object_comments(self):\r
- comments = self.comments.all().order_by('id')\r
- return comments\r
-\r
- def post_get_last_update_info(self):\r
- when = self.added_at\r
- who = self.author\r
- if self.last_edited_at and self.last_edited_at > when:\r
- when = self.last_edited_at\r
- who = self.last_edited_by\r
- comments = self.comments.all()\r
- if len(comments) > 0:\r
- for c in comments:\r
- if c.added_at > when:\r
- when = c.added_at\r
- who = c.user\r
- return when, who
\ No newline at end of file
+import datetime
+import re
+from urllib import quote_plus, urlencode
+from django.db import models, IntegrityError, connection, transaction
+from django.utils.http import urlquote as django_urlquote
+from django.utils.html import strip_tags
+from django.core.urlresolvers import reverse
+from django.contrib.contenttypes import generic
+from django.contrib.contenttypes.models import ContentType
+from django.core.cache import cache
+from django.template.defaultfilters import slugify
+from django.db.models.signals import post_delete, post_save, pre_save, pre_delete
+from django.utils.translation import ugettext as _
+from django.utils.safestring import mark_safe
+from django.contrib.sitemaps import ping_google
+import django.dispatch
+from forum import settings
+import logging
+
+
+class LazyQueryList(object):
+ def __init__(self, model, items):
+ self.model = model
+ self.items = items
+
+ def __getitem__(self, k):
+ return self.model.objects.get(id=self.items[k])
+
+ def __iter__(self):
+ for id in self.items:
+ yield self.model.objects.get(id=id)
+
+ def __len__(self):
+ return len(self.items)
+
+class CachedQuerySet(models.query.QuerySet):
+ def lazy(self):
+ if len(self.query.extra) == 0:
+ return LazyQueryList(self.model, list(self.values_list('id', flat=True)))
+ else:
+ return self
+
+ def obj_from_datadict(self, datadict):
+ obj = self.model()
+ obj.__dict__.update(datadict)
+ return obj
+
+ def get(self, *args, **kwargs):
+ try:
+ pk = [v for (k,v) in kwargs.items() if k in ('pk', 'pk__exact', 'id', 'id__exact'
+ ) or k.endswith('_ptr__pk') or k.endswith('_ptr__id')][0]
+ except:
+ pk = None
+
+ if pk is not None:
+ key = self.model.cache_key(pk)
+ obj = cache.get(key)
+
+ if obj is None:
+ obj = super(CachedQuerySet, self).get(*args, **kwargs)
+ obj.cache()
+ else:
+ obj = self.obj_from_datadict(obj)
+ obj.reset_original_state()
+
+ return obj
+
+ return super(CachedQuerySet, self).get(*args, **kwargs)
+
+class CachedManager(models.Manager):
+ use_for_related_fields = True
+
+ def get_query_set(self):
+ return CachedQuerySet(self.model)
+
+ def get_or_create(self, *args, **kwargs):
+ try:
+ return self.get(*args, **kwargs)
+ except:
+ return super(CachedManager, self).get_or_create(*args, **kwargs)
+
+
+class DenormalizedField(object):
+ def __init__(self, manager, *args, **kwargs):
+ self.manager = manager
+ self.filter = (args, kwargs)
+
+ def setup_class(self, cls, name):
+ dict_name = '_%s_dencache_' % name
+
+ def getter(inst):
+ val = inst.__dict__.get(dict_name, None)
+
+ if val is None:
+ val = getattr(inst, self.manager).filter(*self.filter[0], **self.filter[1]).count()
+ inst.__dict__[dict_name] = val
+ inst.cache()
+
+ return val
+
+ def reset_cache(inst):
+ inst.__dict__.pop(dict_name, None)
+ inst.uncache()
+
+ cls.add_to_class(name, property(getter))
+ cls.add_to_class("reset_%s_cache" % name, reset_cache)
+
+
+class BaseMetaClass(models.Model.__metaclass__):
+ to_denormalize = []
+
+ def __new__(cls, *args, **kwargs):
+ new_cls = super(BaseMetaClass, cls).__new__(cls, *args, **kwargs)
+
+ BaseMetaClass.to_denormalize.extend(
+ [(new_cls, name, field) for name, field in new_cls.__dict__.items() if isinstance(field, DenormalizedField)]
+ )
+
+ return new_cls
+
+ @classmethod
+ def setup_denormalizes(cls):
+ for new_cls, name, field in BaseMetaClass.to_denormalize:
+ field.setup_class(new_cls, name)
+
+
+class BaseModel(models.Model):
+ __metaclass__ = BaseMetaClass
+
+ objects = CachedManager()
+
+ class Meta:
+ abstract = True
+ app_label = 'forum'
+
+ def __init__(self, *args, **kwargs):
+ super(BaseModel, self).__init__(*args, **kwargs)
+ self.reset_original_state(kwargs.keys())
+
+ @classmethod
+ def cache_key(cls, pk):
+ return '%s:%s:%s' % (settings.APP_URL, cls.__name__, pk)
+
+ def reset_original_state(self, reset_fields=None):
+ self._original_state = self._as_dict()
+
+ if reset_fields:
+ self._original_state.update(dict([(f, None) for f in reset_fields]))
+
+ def get_dirty_fields(self):
+ return [f.name for f in self._meta.fields if self._original_state[f.attname] != self.__dict__[f.attname]]
+
+ def _as_dict(self):
+ return dict([(name, getattr(self, name)) for name in
+ ([f.attname for f in self._meta.fields] + [k for k in self.__dict__.keys() if k.endswith('_dencache_')])
+ ])
+
+ def _get_update_kwargs(self):
+ return dict([
+ (f.name, getattr(self, f.name)) for f in self._meta.fields if self._original_state[f.attname] != self.__dict__[f.attname]
+ ])
+
+ def save(self, *args, **kwargs):
+ put_back = [k for k, v in self.__dict__.items() if isinstance(v, models.expressions.ExpressionNode)]
+
+ if self.id:
+ self.__class__.objects.filter(id=self.id).update(**self._get_update_kwargs())
+ else:
+ super(BaseModel, self).save()
+
+ if put_back:
+ try:
+ self.__dict__.update(
+ self.__class__.objects.filter(id=self.id).values(*put_back)[0]
+ )
+ except:
+ logging.error("Unable to read %s from %s" % (", ".join(put_back), self.__class__.__name__))
+ self.uncache()
+
+ self.reset_original_state()
+ self.cache()
+
+ def cache(self):
+ cache.set(self.cache_key(self.id), self._as_dict(), 60 * 60)
+
+ def uncache(self):
+ cache.delete(self.cache_key(self.id))
+
+ def delete(self):
+ self.uncache()
+ super(BaseModel, self).delete()
+
+
+from user import User
+from node import Node, NodeRevision, NodeManager
+from action import Action
+
+
+
+
+