Logo Search packages:      
Sourcecode: zine version File versions  Download package


# -*- coding: utf-8 -*-

    The core models and query helper functions.

    :copyright: (c) 2009 by the Zine Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
from math import ceil, log
from datetime import date, datetime, timedelta
from urlparse import urljoin

from werkzeug.exceptions import NotFound

from zine.database import users, categories, posts, post_links, \
     post_categories, post_tags, tags, comments, groups, group_users, \
     privileges, user_privileges, group_privileges, db
from zine.utils import zeml
from zine.utils.text import gen_slug, build_tag_uri, increment_string
from zine.utils.pagination import Pagination
from zine.utils.crypto import gen_pwhash, check_pwhash
from zine.utils.http import make_external_url
from zine.privileges import Privilege, _Privilege, privilege_attribute, \
from zine.application import get_application, get_request, url_for

#: all kind of states for a post

#: Comment Status

#: moderation modes

00048 class _ZEMLContainer(object):
    """A mixin for objects that have ZEML markup stored."""

    parser_reason = None

00054     def parser_missing(self):
        """If the parser for this post is not available this property will
        be `True`.  If such as post is edited the text area is grayed out
        and tells the user to reinstall the plugin that provides that
        parser.  Because it doesn't know the name of the plugin, the
        preferred was is telling it the parser which is available using
        the `parser` property.
        app = get_application()
        return self.parser not in app.parsers

    def _get_parser(self):
        if self.parser_data is not None:
            return self.parser_data.get('parser')

    def _set_parser(self, value):
        if self.parser_data is None:
            self.parser_data = {}
        self.parser_data['parser'] = value

    parser = property(_get_parser, _set_parser, doc="The name of the parser.")
    del _get_parser, _set_parser

00078     def body(self):
        """The body as ZEML element."""
        if self.parser_data is not None:
            return self.parser_data.get('body')

    def _parse_text(self, text):
        from zine.parsers import parse
        self.parser_data['body'] = parse(text, self.parser, 'post')

    def _get_text(self):
        return self._text

    def _set_text(self, value):
        if self.parser_data is None:
            self.parser_data = {}
        self._text = value

    text = property(_get_text, _set_text, doc="The raw text.")
    del _get_text, _set_text

00099     def find_urls(self):
        """Iterate over all urls in the text.  This will only work if the
        parser for this post is available.  If it's not the behavior is
        undefined.  The urls returned are absolute urls.
        from zine.parsers import parse
        found = set()
        this_url = url_for(self, _external=True)
        tree = parse(self.text, self.parser, 'linksearch')
        for node in tree.query('a[href]'):
            href = urljoin(this_url, node.attributes['href'])
            if href not in found:
                yield href

00115 class _ZEMLDualContainer(_ZEMLContainer):
    """Like the ZEML mixin but with intro and body sections."""

    def _parse_text(self, text):
        from zine.parsers import parse
        self.parser_data['intro'], self.parser_data['body'] = \
            zeml.split_intro(parse(text, self.parser, self.parser_reason))

00124     def intro(self):
        """The intro as zeml element."""
        if self.parser_data is not None:
            return self.parser_data.get('intro')

00130 class UserQuery(db.Query):
    """Add some extra query methods to the user object."""

    def get_nobody(self):
        return AnonymousUser()

    def authors(self):
        return self.filter_by(is_author=True)

00140 class User(object):
    """Represents an user.

    If you change something on this model, even default values, keep in mind
    that the websetup does not use this model to create the admin account
    because at that time the Zine system is not yet ready. Also update
    the code in `zine.websetup.WebSetup.start_setup`.

    query = db.query_property(UserQuery)
    is_somebody = True

    def __init__(self, username, password, email, real_name=u'',
                 description=u'', www=u'', is_author=False):
        self.username = username
        if password is not None:
        self.email = email
        self.www = www
        self.real_name = real_name
        self.description = description
        self.extra = {}
        self.display_name = u'$username'
        self.is_author = is_author

    def is_manager(self):
        return self.has_privilege(ENTER_ADMIN_PANEL)

    def is_admin(self):
        return self.has_privilege(BLOG_ADMIN)

    def _set_display_name(self, value):
        self._display_name = value

    def _get_display_name(self):
        from string import Template
        return Template(self._display_name).safe_substitute(

    display_name = property(_get_display_name, _set_display_name)
    own_privileges = privilege_attribute('_own_privileges')

00189     def privileges(self):
        """A read-only set with all privileges."""
        result = set(self.own_privileges)
        for group in self.groups:
        return frozenset(result)

00196     def has_privilege(self, privilege):
        """Check if the user has a given privilege.  If the user has the
        BLOG_ADMIN privilege he automatically has all the other privileges
        as well.
        return add_admin_privilege(privilege)(self.privileges)

    def set_password(self, password):
        self.pw_hash = gen_pwhash(password)

    def check_password(self, password):
        if self.pw_hash == '!':
            return False
        return check_pwhash(self.pw_hash, password)

    def disable(self):
        self.pw_hash = '!'

    def disabled(self):
        return self.pw_hash == '!'

    def get_url_values(self):
        if self.is_author:
            return 'blog/show_author', {
                'username': self.username
        return self.www or '#'

    def __repr__(self):
        return '<%s %r>' % (

00232 class Group(object):
    """Wraps the group table."""

    def __init__(self, name):
        self.name = name

    privileges = privilege_attribute('_privileges')

    def has_privilege(self, privilege):
        return add_admin_privilege(privilege)(self.privileges)

    def get_url_values(self):
        # TODO: a public view is missing!
        return 'admin/edit_group', {'group_id': self.id}

    def __repr__(self):
        return '<%s %r>' % (

00254 class AnonymousUser(User):
    """Fake model for anonymous users."""
    id = -1
    is_somebody = is_author = False
    display_name = 'Nobody'
    real_name = description = username = ''
    own_privileges = privileges = \
        property(lambda x: frozenset())

    def __init__(self):

    def __nonzero__(self):
        return False

    def check_password(self, password):
        return False

00273 class PostQuery(db.Query):
    """Add some extra methods to the post model."""

00276     def lightweight(self, deferred=None, lazy=('comments',)):
        """Send a lightweight query which deferes some more expensive
        things such as comment queries or even text and parser data.
        args = map(db.lazyload, lazy or ())
        if deferred:
            args.extend(map(db.defer, deferred))
        # undefer the _comment_count query which is used by comment_count
        # for lightweight post objects.  See Post.comment_count for more
        # details.
        if lazy and 'comments' in lazy:
        return self.options(*args)

00290     def type(self, content_type):
        """Filter all posts by a given type."""
        return self.filter_by(content_type=content_type)

00294     def for_index(self):
        """Return all the types for the index."""
        types = get_application().cfg['index_content_types']
        if len(types) == 1:
            return self.filter_by(content_type=types[0].strip())
        return self.filter(Post.content_type.in_([x.strip() for x in types]))

00301     def published(self, ignore_privileges=None):
        """Return a queryset for only published posts."""
        return self.filter(
            (Post.status == STATUS_PUBLISHED) &
            (Post.pub_date <= datetime.utcnow())

00308     def drafts(self, ignore_user=False, user=None):
        """Return a query that returns all drafts for the current user.
        or the user provided or no user at all if `ignore_user` is set.
        if user is None and not ignore_user:
            req = get_request()
            if req and req.user:
                user = req.user
        query = self.filter(Post.status == STATUS_DRAFT)
        if user is not None:
            query = query.filter(Post.author_id == user.id)
        return query

00321     def get_list(self, endpoint=None, page=1, per_page=None,
                 url_args=None, raise_if_empty=True):
        """Return a dict with pagination, the current posts, number of pages,
        total posts and all that stuff for further processing.
        if per_page is None:
            app = get_application()
            per_page = app.cfg['posts_per_page']

        # send the query
        offset = per_page * (page - 1)
        postlist = self.order_by(Post.pub_date.desc()) \

        # if raising exceptions is wanted, raise it
        if raise_if_empty and (page != 1 and not postlist):
            raise NotFound()

        pagination = Pagination(endpoint, page, per_page,
                                self.count(), url_args)

        return {
            'pagination':       pagination,
            'posts':            postlist

00347     def get_archive_summary(self, detail='months', limit=None,
        """Query function to get the archive of the blog. Usually used
        directly from the templates to add some links to the sidebar.
        # XXX: currently we also return months without articles in it.
        # other blog systems do not, but because we use sqlalchemy we have
        # to go with the functionality provided.  Currently there is no way
        # to do date truncating in a database agnostic way.  When this is done
        # ignore_privileges should no longer be a noop
        last = self.filter(Post.pub_date != None) \
        now = datetime.utcnow()

        there_are_more = False
        result = []

        if last is not None:
            now = date(now.year, now.month, now.day)
            oldest = date(last.pub_date.year, last.pub_date.month,
            result = [now]

            there_are_more = False
            if detail == 'years':
                now, oldest = [x.replace(month=1, day=1) for x in now, oldest]
                while True:
                    now = now.replace(year=now.year - 1)
                    if now < oldest:
                    there_are_more = True
            elif detail == 'months':
                now, oldest = [x.replace(day=1) for x in now, oldest]
                while limit is None or len(result) < limit:
                    if not now.month - 1:
                        now = now.replace(year=now.year - 1, month=12)
                        now = now.replace(month=now.month - 1)
                    if now < oldest:
                    there_are_more = True
            elif detail == 'days':
                while limit is None or len(result) < limit:
                    now = now - timedelta(days=1)
                    if now < oldest:
                    there_are_more = True
                raise ValueError('detail must be years, months, or days')

        return {
            detail:     result,
            'more':     there_are_more,
            'empty':    not result

00409     def latest(self, ignore_privileges=False):
        """Filter for the latest n posts."""
        return self.published(ignore_privileges=ignore_privileges)

00413     def date_filter(self, year, month=None, day=None):
        """Filter all the items that match the given date."""
        if month is None:
            return self.filter(
                (Post.pub_date >= datetime(year, 1, 1)) &
                (Post.pub_date < datetime(year + 1, 1, 1))
        elif day is None:
            return self.filter(
                (Post.pub_date >= datetime(year, month, 1)) &
                (Post.pub_date < (month == 12 and
                               datetime(year + 1, 1, 1) or
                               datetime(year, month + 1, 1)))
        return self.filter(
            (Post.pub_date >= datetime(year, month, day)) &
            (Post.pub_date < datetime(year, month, day) +

00433     def search(self, query):
        """Search for posts by a query."""
        # XXX: use a sophisticated search
        q = self
        for word in query.split():
            q = q.filter(
                posts.c.body.like('%%%s%%' % word) |
                posts.c.intro.like('%%%s%%' % word) |
                posts.c.title.like('%%%s%%' % word)
        return q.all()

00446 class Post(_ZEMLDualContainer):
    """Represents one blog post."""

    query = db.query_property(PostQuery)
    parser_reason = 'post'

    def __init__(self, title, author, text, slug=None, pub_date=None,
                 last_update=None, comments_enabled=True,
                 pings_enabled=True, status=STATUS_PUBLISHED,
                 parser=None, uid=None, content_type='entry'):
        app = get_application()
        self.content_type = content_type
        self.title = title
        self.author = author
        if parser is None:
            parser = app.cfg['default_parser']

        self.parser = parser
        self.text = text or u''
        self.extra = {}

        self.comments_enabled = comments_enabled
        self.pings_enabled = pings_enabled
        self.status = status

        # set times now, they depend on status being set
        if last_update is not None:
            self.last_update = last_update

        # now bind the slug for which we need the times set.

        # generate a UID if none is given
        if uid is None:
            uid = build_tag_uri(app, self.pub_date, content_type, self.slug)
        self.uid = uid

    def _privileges(self):
        return get_application().content_type_privileges[self.content_type]

00489     def EDIT_OWN_PRIVILEGE(self):
        """The edit-own privilege for this content type."""
        return self._privileges[1]

00494     def EDIT_OTHER_PRIVILEGE(self):
        """The edit-other privilege for this content type."""
        return self._privileges[2]

00499     def root_comments(self):
        """Return only the comments for this post that don't have a parent."""
        return [x for x in self.comments if x.parent is None]

00504     def visible_comments(self):
        """Return only the comments for this post that are visible to
        the user.
        return [x for x in self.comments if x.visible]

00511     def visible_root_comments(self):
        """Return only the comments for this post that are visible to
        the user and that don't have a parent.
        return [x for x in self.comments if x.visible and x.parent is None]

00518     def comment_count(self):
        """The number of visible comments."""
        req = get_request()

        # if the model was loaded with .lightweight() there are no comments
        # but a _comment_count we can use.
        if not db.attribute_loaded(self, 'comments'):
            return self._comment_count

        # otherwise the comments are already available and we can savely
        # filter it.
        if req.user.is_manager:
            return len(self.comments)
        return len([x for x in self.comments if not x.blocked])

00534     def comment_feed_url(self):
        """The link to the comment feed."""
        return make_external_url(self.slug.rstrip('/') + '/feed.atom')

00539     def is_draft(self):
        """True if this post is unpublished."""
        return self.status == STATUS_DRAFT

00543     def set_auto_slug(self):
        """Generate a slug for this post."""
        slug = gen_slug(self.title)
        if not slug:
            slug = self.pub_date.strftime('%H:%M')
        prefix = get_application().cfg['blog_url_prefix'].lstrip('/')
        if prefix:
            prefix += '/'
        full_slug = u'%s%04d/%d/%d/%s' % (

        if full_slug != self.slug:
            while Post.query.autoflush(False).filter_by(slug=full_slug) \
                full_slug = increment_string(full_slug)
            self.slug = full_slug

00565     def touch_times(self, pub_date=None):
        """Touches the times for this post.  If the pub_date is given the
        `pub_date` is changed to the given date.  If it's not given the
        current time is assumed if the post status is set to published,
        otherwise it's set to `None`.

        Additionally the `last_update` is always set to now.
        now = datetime.utcnow()
        if pub_date is None and self.status == STATUS_PUBLISHED:
            pub_date = now
        self.pub_date = pub_date
        self.last_update = now

00579     def bind_slug(self, slug=None):
        """Binds a new slug to the post.  If the slug is `None`/empty a new
        automatically generated slug is created.  Otherwise that slug is
        used and assigned.
        if not slug:
            self.slug = slug

00589     def bind_tags(self, tags):
        """Rebinds the tags to a list of tags (strings, not tag objects)."""
        current_map = dict((x.name, x) for x in self.tags)
        currently_attached = set(x.name for x in self.tags)
        new_tags = set(tags)

        # delete outdated tags
        for name in currently_attached.difference(new_tags):

        # add new tags
        for name in new_tags.difference(currently_attached):

00603     def bind_categories(self, categories):
        """Rebinds the categories to the list passed.  The list of objects
        must be a list of category objects.
        currently_attached = set(self.categories)
        new_categories = set(categories)

        # delete outdated categories
        for category in currently_attached.difference(new_categories):

        # attach new categories
        for category in new_categories.difference(currently_attached):

00618     def can_edit(self, user=None):
        """Checks if the given user (or current user) can edit this post."""
        if user is None:
            user = get_request().user

        return (
            user.has_privilege(self.EDIT_OTHER_PRIVILEGE) or
            (self.author == user and

00629     def can_read(self, user=None):
        """Check if the current user or the user provided can read-access
        this post. If there is no user there must be a request object
        for this thread defined.
        # published posts are always accessible
        if self.status == STATUS_PUBLISHED and \
           self.pub_date <= datetime.utcnow():
            return True

        if user is None:
            user = get_request().user

        # users that are allowed to look at drafts may pass
        if user.has_privilege(VIEW_DRAFTS):
            return True

        # if we have the privilege to edit other entries or if we are
        # a blog administrator we can always look at posts.
        if user.has_privilege(self.EDIT_OTHER_PRIVILEGE):
            return True

        # otherwise if the user has the EDIT_OWN_PRIVILEGE and the
        # author of the post, he may look at it as well
        if user.id == self.author_id and \
            return True

        return False

00660     def is_published(self):
        """`True` if the post is visible for everyone."""
        return self.can_read(AnonymousUser())

00665     def is_scheduled(self):
        """True if the item is scheduled for appearing."""
        return self.status == STATUS_PUBLISHED and \
               self.pub_date > datetime.utcnow()

    def get_url_values(self):
        return self.slug

    def __repr__(self):
        return '<%s %r>' % (

00680 class PostLink(object):
    """Represents a link in a post.  This can be used for podcasts or other
    resources that require ``<link>`` categories.

    def __init__(self, post, href, rel='alternate', type=None, hreflang=None,
                 title=None, length=None):
        self.post = post
        self.href = href
        self.rel = rel
        self.type = type
        self.hreflang = hreflang
        self.title = title
        self.length = length

00695     def as_dict(self):
        """Return the values as dict.  Useful for feed building."""
        result = {'href': href}
        for key in 'rel', 'type', 'hreflang', 'title', 'length':
            value = getattr(self, key, None)
            if value is not None:
                result[key] = value
        return result

    def __repr__(self):
        return '<%s %r>' % (

00711 class CategoryQuery(db.Query):
    """Also categories have their own manager."""

00714     def get_or_create(self, slug, name=None):
        """Get the category for this slug or create it if it does not exist."""
        category = self.filter_by(slug=slug).first()
        if category is None:
            if name is None:
                name = slug
            category = Category(name, slug=slug)
        return category

00724 class Category(object):
    """Represents a category."""

    query = db.query_property(CategoryQuery)

    def __init__(self, name, description='', slug=None):
        self.name = name
        if slug is None:
            self.slug = slug
        self.description = description

00737     def set_auto_slug(self):
        """Generate a slug for this category."""
        full_slug = gen_slug(self.name)
        if not full_slug:
            # if slug generation failed we select the highest category
            # id as base for slug generation.
            category = Category.query.autoflush(False) \
            full_slug = unicode(category and category.id or u'1')
        if full_slug != self.slug:
            while Category.query.autoflush(False) \
                full_slug = increment_string(full_slug)
            self.slug = full_slug

    def get_url_values(self):
        return 'blog/show_category', {
            'slug':     self.slug

    def __repr__(self):
        return '<%s %r>' % (

00764 class CommentQuery(db.Query):
    """The manager for comments"""

00767     def approved(self):
        """Return only the approved comments."""
        return self.filter(Comment.status == COMMENT_MODERATED)

00771     def blocked(self):
        """Filter all blocked comments.  Blocked comments are all comments but
        unmoderated and moderated comments.
        return self.filter(Comment.status.in_([COMMENT_BLOCKED_USER,
00778     def unmoderated(self):
        """Filter all the unmoderated comments and comments blocked by a user
        or system.
        return self.filter(Comment.status.in_([COMMENT_UNMODERATED,

00786     def spam(self):
        """Filter all the spam comments."""
        return self.filter(Comment.status == COMMENT_BLOCKED_SPAM)

00790     def latest(self, limit=None, ignore_privileges=False, ignore_blocked=True):
        """Filter the list of non blocked comments for anonymous users or
        all comments for admin users.
        query = self

        # only the approved if blocked are ignored
        if ignore_blocked:
            query = query.approved()

        # otherwise if we don't ignore the privileges we only want
        # the approved if the user does not have the MODERATE_COMMENTS
        # privileges.
        elif not ignore_privileges:
            req = get_request()
            if req:
                user = req.user
                if not user.has_privilege(MODERATE_COMMENTS):
                    query = query.approved()

        return query

00812     def comments_for_post(self, post):
        """Return all comments for the blog post."""
        return self.filter(Comment.post_id == post.id)

00817 class Comment(_ZEMLContainer):
    """Represent one comment."""

    query = db.query_property(CommentQuery)
    parser_reason = 'comment'

    def __init__(self, post, author, text, email=None, www=None, parent=None,
                 pub_date=None, submitter_ip='', parser=None,
                 is_pingback=False, status=COMMENT_MODERATED):
        self.post = post
        if isinstance(author, basestring):
            self.user = None
            self._author = author
            self._email = email
            self._www = www
            assert email is www is None, \
                'email and www can only be provided if the author is ' \
                'an anonmous user'
            self.user = author

        if parser is None:
            parser = get_application().cfg['comment_parser']
        self.parser = parser
        self.text = text or ''
        self.parent = parent
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.pub_date = pub_date
        self.blocked_msg = None
        self.submitter_ip = submitter_ip
        self.is_pingback = is_pingback
        self.status = status

00851     def _union_property(attribute, user_attribute=None):
        """An attribute that can exist on a user and the comment."""
        user_attribute = user_attribute or attribute
        attribute = '_' + attribute
        def get(self):
            if self.user:
                return getattr(self.user, user_attribute)
            return getattr(self, attribute)
        def set(self, value):
            if self.user:
                raise TypeError('can\'t set this attribute if the comment '
                                'does not belong to an anonymous user')
            setattr(self, attribute, value)
        return property(get, set)

    email = _union_property('email')
    www = _union_property('www')
    author = _union_property('author', 'display_name')
    del _union_property

00872     def anonymous(self):
        """True if this comment is an anonymous comment."""
        return self.user is None

00877     def requires_moderation(self):
        """This is `True` if the comment requires moderation with the
        current moderation settings.  This does not check if the comment
        is already moderated.
        if not self.anonymous:
            return False
        moderate = get_application().cfg['moderate_comments']
        if moderate == MODERATE_ALL:
            return True
        elif moderate == MODERATE_NONE:
            return False
        return db.execute(comments.select(
            (comments.c.author == self._author) &
            (comments.c.email == self._email) &
            (comments.c.status == COMMENT_MODERATED)
        )).fetchone() is None

00895     def make_visible_for_request(self, request=None):
        """Make the comment visible for the current request."""
        if request is None:
            request = get_request()
        comments = set(request.session.get('visible_comments', ()))
        request.session['visible_comments'] = tuple(comments)

00903     def visible_for_user(self, user=None):
        """Check if the current user or the user given can see this comment"""
        if not self.blocked:
            return True
        if user is None:
            user = get_request().user
        return user.has_privilege(MODERATE_COMMENTS)

00912     def visible(self):
        """Check the current session it can see the comment or check against the
        current user.  To display a comment for a request you can use the
        `make_visible_for_request` function.  This is useful to show a comment
        to a user that submited a comment which is not yet moderated.
        request = get_request()
        if self.id in request.session.get('visible_comments', ()):
            return True
        return self.visible_for_user(request.user)

00924     def visible_children(self):
        """Only the children that are visible for the current user."""
        return [x for x in self.children if x.visible]

00929     def blocked(self):
        """This is true if the status is anything but moderated."""
        return self.status != COMMENT_MODERATED

00934     def is_spam(self):
        """This is true if the comment is currently flagges as spam."""
        return self.status == COMMENT_BLOCKED_SPAM

00939     def is_unmoderated(self):
        """True if the comment is not yet approved."""
        return self.status == COMMENT_UNMODERATED

    def get_url_values(self):
        return url_for(self.post) + '#comment-%d' % self.id

    def __repr__(self):
        return '<%s %r>' % (

class TagQuery(db.Query):

    def get_cloud(self, max=None, ignore_privileges=False):
        """Get a categorycloud."""
        # XXX: ignore_privileges is currently ignored and no privilege
        # checking is performed.  As a matter of fact only published posts
        # appear in the cloud.

        # get a query
        pt = post_tags.c
        p = posts.c
        t = tags.c

        q = ((pt.tag_id == t.tag_id) &
             (pt.post_id == p.post_id) &
             (p.status == STATUS_PUBLISHED) &
             (p.pub_date >= datetime.utcnow()))

        s = db.select([t.slug, t.name, db.func.count(p.post_id).label('s_count')],
                      (pt.tag_id == t.tag_id) &
                      (pt.post_id == p.post_id),
                      group_by=[t.slug, t.name]).alias('post_count_query').c

        options = {'order_by': [db.asc(s.s_count)]}
        if max is not None:
            options['limit'] = max

        # the label statement circumvents a bug for sqlite3 on windows
        # see #65
        q = db.select([s.slug, s.name, s.s_count.label('s_count')], **options)

        items = [{
            'slug':     row.slug,
            'name':     row.name,
            'count':    row.s_count,
            'size':     100 + log(row.s_count or 1) * 20
        } for row in db.execute(q)]

        items.sort(key=lambda x: x['name'].lower())
        return items

00995 class Tag(object):
    """A single tag."""
    query = db.query_property(TagQuery)

    def __init__(self, name, slug=None):
        self.name = name
        if slug is None:
            self.slug = slug

    def get_or_create(name):
        tag = Tag.query.filter_by(name=name).first()
        if tag is not None:
            return tag
        return Tag(name)

    def set_auto_slug(self):
        full_slug = gen_slug(self.name)
        if not full_slug:
            # if slug generation failed we select the highest category
            # id as base for slug generation.
            tag = Tag.query.autoflush(False).order_by(Tag.id.desc()).first()
            full_slug = unicode(tag and tag.id or u'1')
        if full_slug != self.slug:
            while Tag.query.autoflush(False) \
                full_slug = increment_string(full_slug)
            self.slug = full_slug

    def get_url_values(self):
        return 'blog/show_tag', {'slug': self.slug}

    def __repr__(self):
        return u'<%s %r>' % (

# connect the tables.
db.mapper(User, users, properties={
    'id':               users.c.user_id,
    'display_name':     db.synonym('_display_name', map_column=True),
    'posts':            db.dynamic_loader(Post,
                                          backref=db.backref('author', lazy=False),
                                          cascade='all, delete, delete-orphan'),
    'comments':         db.dynamic_loader(Comment,
                                          backref=db.backref('user', lazy=False),
                                          cascade='all, delete, delete-orphan'),
    '_own_privileges':  db.relation(_Privilege, lazy=True,
                                    cascade='all, delete')
db.mapper(Group, groups, properties={
    'id':               groups.c.group_id,
    'users':            db.dynamic_loader(User, backref=db.backref('groups', lazy=True),
    '_privileges':      db.relation(_Privilege, lazy=True,
                                    cascade='all, delete')
db.mapper(_Privilege, privileges, properties={
    'id':               privileges.c.privilege_id,
db.mapper(Category, categories, properties={
    'id':               categories.c.category_id,
    'posts':            db.dynamic_loader(Post, secondary=post_categories)
}, order_by=categories.c.name)
db.mapper(Comment, comments, properties={
    'id':           comments.c.comment_id,
    'text':         db.synonym('_text', map_column=True),
    'author':       db.synonym('_author', map_column=True),
    'email':        db.synonym('_email', map_column=True),
    'www':          db.synonym('_www', map_column=True),
    'children':     db.relation(Comment,
        primaryjoin=comments.c.parent_id == comments.c.comment_id,
        backref=db.backref('parent', remote_side=[comments.c.comment_id],
                           primaryjoin=comments.c.parent_id == comments.c.comment_id),
}, order_by=comments.c.pub_date.desc())
db.mapper(PostLink, post_links, properties={
    'id':           post_links.c.link_id,
db.mapper(Tag, tags, properties={
    'id':           tags.c.tag_id,
    'posts':        db.dynamic_loader(Post, secondary=post_tags)
}, order_by=tags.c.name)
db.mapper(Post, posts, properties={
    'id':               posts.c.post_id,
    'text':             db.synonym('_text', map_column=True),
    'comments':         db.relation(Comment, backref='post',
                                    primaryjoin=posts.c.post_id ==
                                    cascade='all, delete, delete-orphan'),
    'links':            db.relation(PostLink, backref='post',
                                    cascade='all, delete, delete-orphan'),
    'categories':       db.relation(Category, secondary=post_categories, lazy=False,
    'tags':             db.relation(Tag, secondary=post_tags, lazy=False,
    '_comment_count':   db.column_property(
                  (comments.c.post_id == posts.c.post_id) &
                  (comments.c.status == COMMENT_MODERATED)
        ).label('comment_count'), deferred=True)
}, order_by=posts.c.pub_date.desc())

Generated by  Doxygen 1.6.0   Back to index