Exemple #1
0
class GeometryColumns(models.Model):
    """
    The 'geometry_columns' table from SpatiaLite.
    """
    f_table_name = models.CharField(max_length=256)
    f_geometry_column = models.CharField(max_length=256)
    type = models.CharField(max_length=30)
    coord_dimension = models.IntegerField()
    srid = models.IntegerField(primary_key=True)
    spatial_index_enabled = models.IntegerField()

    class Meta:
        db_table = 'geometry_columns'
        managed = False

    @classmethod
    def table_name_col(cls):
        """
        Returns the name of the metadata column used to store the
        the feature table name.
        """
        return 'f_table_name'

    @classmethod
    def geom_col_name(cls):
        """
        Returns the name of the metadata column used to store the
        the feature geometry column.
        """
        return 'f_geometry_column'

    def __unicode__(self):
        return "%s.%s - %dD %s field (SRID: %d)" % \
               (self.f_table_name, self.f_geometry_column,
                self.coord_dimension, self.type, self.srid)
Exemple #2
0
class SpatialRefSys(models.Model, SpatialRefSysMixin):
    """
    The 'spatial_ref_sys' table from SpatiaLite.
    """
    srid = models.IntegerField(primary_key=True)
    auth_name = models.CharField(max_length=256)
    auth_srid = models.IntegerField()
    ref_sys_name = models.CharField(max_length=256)
    proj4text = models.CharField(max_length=2048)

    @property
    def wkt(self):
        from my_django.contrib.gis.gdal import SpatialReference
        return SpatialReference(self.proj4text).wkt

    class Meta:
        db_table = 'spatial_ref_sys'
        managed = False
class RepositoryUser(models.Model):
    """A User of a repository"""
    source_repository = models.ForeignKey(HgRepository)
    user = models.ForeignKey(User)
    permission = models.IntegerField(_('Permission'), choices=PERM_CHOICES)

    def __unicode__(self):
        out = u"%s of %s with %s permission" % (
            self.user, self.source_repository, self.get_permission_display())

        return out
class SpatialRefSys(models.Model, SpatialRefSysMixin):
    """
    The 'spatial_ref_sys' table from PostGIS. See the PostGIS
    documentaiton at Ch. 4.2.1.
    """
    srid = models.IntegerField(primary_key=True)
    auth_name = models.CharField(max_length=256)
    auth_srid = models.IntegerField()
    srtext = models.CharField(max_length=2048)
    proj4text = models.CharField(max_length=2048)

    class Meta:
        db_table = 'spatial_ref_sys'
        managed = False

    @property
    def wkt(self):
        return self.srtext

    @classmethod
    def wkt_col(cls):
        return 'srtext'
Exemple #5
0
class Forum(models.Model):
    slug = models.SlugField(unique=True)
    name = models.CharField(max_length=255)
    group = models.CharField(max_length=255, blank=True)
    ordering = models.IntegerField(default=0)
    # --
    is_forum = models.BooleanField(default=True)

    class Meta:
        ordering = ['ordering', 'group']

    def __unicode__(self):
        return self.name

    @models.permalink
    def get_absolute_url(self):
        return 'cicero.views.forum', [self.slug]
class Comment(models.Model):
    repo = models.ForeignKey(Repo, on_delete=models.CASCADE)
    rev = models.CharField(max_length=200)#tag
    file_path = models.CharField(max_length=200)#tag
    line = models.IntegerField()
    content = models.CharField(max_length=200)
Exemple #7
0
class Profile(models.Model):
    #    latitude = models.CharField(max_length=25, blank=True, null=True)

    user = fields.AutoOneToOneField(User,
                                    related_name='cicero_profile',
                                    primary_key=True)
    filter = models.CharField(u'Фильтр',
                              max_length=50,
                              choices=[(k, k) for k in filters.keys()],
                              default='agd')
    read_articles = fields.RangesField(editable=False)
    moderator = models.BooleanField(default=False)
    # --
    is_banned = models.BooleanField(default=False)
    # --
    last_post = models.DateField(auto_now=False, blank=True, null=True)
    last_edit = models.DateField(auto_now=False, blank=True, null=True)
    # --
    max_posts = models.IntegerField()
    today_posts = models.IntegerField()
    # --
    max_topics = models.IntegerField()
    today_topics = models.IntegerField()
    # --
    max_edits = models.IntegerField()
    today_edits = models.IntegerField()
    # --
    total_posts = models.IntegerField()
    carma = models.IntegerField()
    today_change_carmas = models.IntegerField()
    max_change_carmas = models.IntegerField()
    # --
    last_ip = models.IPAddressField(default='127.0.0.1')
    user_agent = models.CharField(max_length=255, default='')
    # --
    registered_ip = models.IPAddressField(default='127.0.0.1')
    registered_date = models.DateField(auto_now=False)
    # --
    max_repos = models.IntegerField()
    used_repos = models.IntegerField()

    #def __unicode__(self):
    #    try:
    #        #return unicode(self.user.scipio_profile)
    #        return unicode(self.user.scipio_profile)
    #    except ScipioProfile.DoesNotExist:
    #        pass
    #    return unicode(self.user)

    #def save(self, **kwargs):
    #self.user = self.username
    #if not self.mutant:
    #    self.generate_mutant()
    #    super(Profile, self).save(**kwargs)

    #def get_absolute_url(self):
    #    return reverse('profile', args=[self.user_id])

    #def generate_mutant(self):
    #    '''
    #    Создает, если возможно, картинку мутанта из OpenID.
    #    '''
    #    if self.mutant and os.path.exists(self.mutant.path):
    #        os.remove(self.mutant.path)
    #    if not settings.CICERO_OPENID_MUTANT_PARTS:
    #        return
    #        try:
    #            content = StringIO()
    #            mutant(self.user.scipio_profile.openid).save(content, 'PNG')
    #            self.mutant.save('%s.png' % self._get_pk_val(), ContentFile(content.getvalue()))
    #        except ScipioProfile.DoesNotExist:
    #            pass

    #    scipio.signals.created.connect(lambda sender, profile, **kwargs: profile.user.cicero_profile.generate_mutant())

    def unread_topics(self):
        '''
        Непрочитанные топики пользователя во всех форумах
        '''
        query = Q()
        for range in self.read_articles:
            query = query | Q(article__id__range=range)
        return Topic.objects.exclude(query).distinct()

    def set_news(self, objects):
        '''
        Проставляет признаки наличия новых статей переданным топикам или форумам
        '''
        if len(objects) == 0:
            return
        ids = [str(o.id) for o in objects]
        tables = 'cicero_article a, cicero_topic t'
        condition = 'topic_id = t.id' \
                    ' and a.deleted is null and a.spam_status = \'clean\'' \
                    ' and t.deleted is null and t.spam_status = \'clean\'' \
                    ' and t.created >= %s'
        if isinstance(objects[0], Forum):
            field_name = 'forum_id'
            condition += ' and forum_id in (%s)' % ','.join(ids)
        else:
            field_name = 'topic_id'
            condition += ' and topic_id in (%s)' % ','.join(ids)
        ranges = ' or '.join(
            ['a.id between %s and %s' % range for range in self.read_articles])
        condition += ' and not (%s)' % ranges
        query = 'select %s, count(1) as c from %s where %s group by 1' % (
            field_name, tables, condition)
        old_topic_age = datetime.now().date() - timedelta(
            settings.CICERO_OLD_TOPIC_AGE)
        cursor = connection.cursor()
        cursor.execute(query, [old_topic_age])
        counts = dict(cursor.fetchall())
        for obj in objects:
            obj.new = counts.get(obj.id, 0)

    def add_read_articles(self, articles):
        '''
        Добавляет новые статьи к списку прочитанных.

        Статьи передаются в виде queryset.
        '''

        return

        # Нужно еще раз считать read_articles с "for update", чтобы параллельные транзакции
        # не затирали друг друга
        cursor = connection.cursor()
        sql = 'select read_articles from %s where %s = %%s for update' % (
            self._meta.db_table, self._meta.pk.attname)
        cursor.execute('begin')
        cursor.execute(sql, [self._get_pk_val()])
        self.read_articles = cursor.fetchone()[0]

        query = Q()
        for range in self.read_articles:
            query = query | Q(id__range=range)
        ids = [a['id'] for a in articles.exclude(query).values('id')]
        merged = self.read_articles
        for range in ranges.compile_ranges(ids):
            merged = ranges.merge_range(range, merged)
        try:
            article = Article.objects.filter(
                created__lt=date.today() -
                timedelta(settings.CICERO_UNREAD_TRACKING_PERIOD)).order_by(
                    '-created')[0]
            merged = ranges.merge_range((0, article.id), merged)
        except IndexError:
            pass
        if self.read_articles != merged:
            self.read_articles = merged
            return True
        else:
            return False

    def can_change_article(self, article):
        return self.moderator or self.user.is_superuser or (
            not article.from_guest() and article.author_id == self.user_id)

    def can_change_topic(self, topic):
        return self.can_change_article(topic.article_set.all()[0])

    def topics(self):
        return Topic.objects.filter(
            article__author=self).distinct().select_related('forum')