示例#1
0
class Link(db.Model):

    __tablename__ = "links"

    PER_PAGE = 80

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(50), nullable=False)
    link = db.Column(db.String(100), nullable=False)
    logo = db.Column(db.String(100))
    description = db.Column(db.Unicode(100))
    email = db.Column(db.String(50))
    passed = db.Column(db.Boolean, default=False)
    created_date = db.Column(db.DateTime, default=datetime.utcnow)

    class Permissions(object):
        def __init__(self, obj):
            self.obj = obj

    def __init__(self, *args, **kwargs):
        super(Link, self).__init__(*args, **kwargs)

    def __str__(self):
        return self.name

    def __repr__(self):
        return "<%s>" % self

    @cached_property
    def permissions(self):
        return self.Permissions(self)

    @cached_property
    def json(self):
        return dict(id=self.id,
                    name=self.name,
                    url=self.link,
                    logo=self.logo,
                    description=self.description,
                    created_date=self.created_date)

    @cached_property
    def item(self):
        return storage(self.json)
示例#2
0
class Tweet(db.Model):

    __tablename__ = 'tweets'

    id = db.Column(db.Integer, primary_key=True)

    user_id = db.Column(db.Integer,
                        db.ForeignKey(User.id, ondelete='CASCADE'),
                        nullable=False,
                        unique=True)

    server = db.Column(db.String(50))
    token = db.Column(db.String(50))
    token_secret = db.Column(db.String(50))

    def __init__(self, *args, **kwargs):
        super(Tweet, self).__init__(*args, **kwargs)

    def __str__(self):
        return "Tweet: %s" % self.id

    def __repr__(self):
        return "<%s>" % self
示例#3
0
class Act(Post):
    __tablename__ = 'acts'
    __mapper_args__ = {'polymorphic_identity': 'acts'}

    id = db.Column('id', db.Integer, db.ForeignKey('posts.id'), primary_key=True)
    photo = db.Column(db.String(200), default="")
    linkinfo = db.Column(db.String(200), default="")
    start_date = db.Column(db.DateTime, default=datetime.utcnow)
    finish_date = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    sign_start_date = db.Column(db.DateTime, default=datetime.utcnow)
    sign_finish_date = db.Column(db.DateTime, default=datetime.utcnow)
    limit_num = db.Column(db.Integer(), default=500)
    pay_count = db.Column(db.Integer(), default=0)
    location = db.Column(db.UnicodeText())

    [STATUS_PUBLIC, STATUS_DRAFT, STATUS_PRIVATE, STATUS_CANCEL, STATUS_DELETED] = range(5)
    status = db.Column(db.Integer(), nullable=False, default=STATUS_PUBLIC)

    #经度
    latitude = db.Column(db.Float())
    longitude = db.Column(db.Float())
    zoomlevel = db.Column(db.Integer())

    city_id = db.Column(db.Integer, db.ForeignKey('city.id'), default=1)
    city_name = association_proxy('city'
            , 'name'
            , creator=City._find_or_create)

    @cached_property
    def url(self):
        return route.url_for('act_view',
                    self.slug.encode('utf8'))

    @property
    def parts(self):
        parts = Participate.query.filter(Participate.act_id==self.id)
        return [rel.user for rel in parts]
示例#4
0
class UserCode(db.Model):

    __tablename__ = 'usercode'

    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(20), nullable=False)
    role = db.Column(db.Integer, default=User.MEMBER)

    def __init__(self, *args, **kwargs):
        super(UserCode, self).__init__(*args, **kwargs)

    def __str__(self):
        return self.code

    def __repr__(self):
        return "<%s>" % self
示例#5
0
class City(db.Model):
    __tablename__ = 'city'
    __table_args__ = (
        db.UniqueConstraint('name'),
        )

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(50), nullable=False)
    name_pinyin = db.Column(db.String(50))
    acts = db.relationship("Act", backref='city', order_by='desc(Act.start_date)')
    #usercity = db.relationship("Author", backref='city', order_by='desc(MbaUser.creation_date)')

    @classmethod
    def _find_or_create(cls, name):
        with db.session.no_autoflush:
            obj = db.session.query(City).filter_by(name=name).first()
        if obj is None:
            obj = City(name=name)
        return obj
示例#6
0
class Post(db.Model):

    __tablename__ = 'posts'

    PER_PAGE = 40

    query_class = PostQuery

    id = db.Column(db.Integer, primary_key=True)

    author_id = db.Column(db.Integer,
                          db.ForeignKey(User.id, ondelete='CASCADE'),
                          nullable=False)

    _title = db.Column("title", db.Unicode(100), index=True)
    _slug = db.Column("slug", db.Unicode(50), unique=True, index=True)
    content = db.Column(db.UnicodeText)
    created_date = db.Column(db.DateTime, default=datetime.utcnow)
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    post_type = db.Column(db.String(32), nullable=False)

    _tags = db.Column("tags", db.Unicode(100), index=True)

    author = db.relation(User, innerjoin=True, lazy="joined")

    __mapper_args__ = {'order_by': id.desc(), 'polymorphic_on': post_type, 'polymorphic_identity': 'posts'}

    class Permissions(object):

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

        @cached_property
        def edit(self):
            return Permission(UserNeed(self.obj.author_id))

        @cached_property
        def delete(self):
            return Permission(UserNeed(self.obj.author_id))


    def __init__(self, *args, **kwargs):
        super(Post, self).__init__(*args, **kwargs)

    def __str__(self):
        return self.title

    def __repr__(self):
        return "<%s>" % self

    @cached_property
    def permissions(self):
        return self.Permissions(self)

    def _get_title(self):
        return self._title

    def _set_title(self, title):
        self._title = title.lower().strip()
        if self.slug is None:
            self.slug = slugify(title)[:50]

    title = db.synonym("_title", descriptor=property(_get_title, _set_title))

    def _get_slug(self):
        return self._slug

    def _set_slug(self, slug):
        if slug:
            self._slug = slugify(slug)

    slug = db.synonym("_slug", descriptor=property(_get_slug, _set_slug))

    def _get_tags(self):
        return self._tags

    def _set_tags(self, tags):

        self._tags = tags

        if self.id:
            # ensure existing tag references are removed
            d = db.delete(post_tags, post_tags.c.post_id==self.id)
            db.engine.execute(d)

        for tag in set(self.taglist):

            slug = slugify(tag)

            tag_obj = Tag.query.filter(Tag.slug==slug).first()
            if tag_obj is None:
                tag_obj = Tag(name=tag, slug=slug)
                db.session.add(tag_obj)

            tag_obj.posts.append(self)

    tags = db.synonym("_tags", descriptor=property(_get_tags, _set_tags))

    @cached_property
    def url(self):
        return route.url_for('post_view',
                    self.created_date.year,
                    self.created_date.month,
                    self.created_date.day,
                    self.slug.encode('utf8'))

    @cached_property
    def taglist(self):
        if self.tags is None:
            return []

        tags = [t.strip() for t in self.tags.split(",")]
        return [t for t in tags if t]

    @cached_property
    def linked_taglist(self):
        return [(tag, route.url_for('tag', slugify(tag))) \
                    for tag in self.taglist]

    @cached_property
    def prev_post(self):
        prev_post = Post.query.filter(Post.created_date < self.created_date) \
                              .first()
        return prev_post

    @cached_property
    def next_post(self):
        next_post = Post.query.filter(Post.created_date > self.created_date) \
                              .order_by('created_date').first()
        return next_post

    @cached_property
    def summary(self):
        s = re.findall(r'(<hr>)', self.content)
        if not s:
            return self.content
        p = s[0]
        return endtags(self.content.split(p)[0])

    @property
    def comments(self):
        """
        Returns comments in tree. Each parent comment has a "comments"
        attribute appended and a "depth" attribute.
        """
        comments = Comment.query.filter(Comment.post_id==self.id).all()

        def _get_comments(parent, depth):

            parent.comments = []
            parent.depth = depth

            for comment in comments:
                if comment.parent_id == parent.id:
                    parent.comments.append(comment)
                    _get_comments(comment, depth + 1)

        parents = [c for c in comments if c.parent_id is None]

        for parent in parents:
            _get_comments(parent, 0)

        return parents

    @cached_property
    def json(self):
        return dict(id=self.id,
                    title=self.title,
                    content=self.content,
                    author=self.author.username)
示例#7
0
class Comment(db.Model):

    __tablename__ = "comments"

    query_class = CommentQuery

    PER_PAGE = 40

    id = db.Column(db.Integer, primary_key=True)

    post_id = db.Column(db.Integer,
                        db.ForeignKey(Post.id, ondelete='CASCADE'),
                        nullable=False)

    author_id = db.Column(db.Integer,
                          db.ForeignKey(User.id, ondelete='CASCADE'))

    parent_id = db.Column(db.Integer,
                          db.ForeignKey("comments.id", ondelete='CASCADE'))

    email = db.Column(db.String(50))
    nickname = db.Column(db.Unicode(50))
    website = db.Column(db.String(100))

    comment = db.Column(db.UnicodeText)
    created_date = db.Column(db.DateTime, default=datetime.utcnow)

    ip = db.Column(db.String(20))

    _author = db.relation(User, backref="posts", lazy="joined")

    post = db.relation(Post, innerjoin=True, lazy="joined")

    parent = db.relation('Comment', lazy="joined", remote_side=[id])

    __mapper_args__ = {'order_by' : id.asc()}


    class Permissions(object):

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

        @cached_property
        def edit(self):
            return Permission(UserNeed(self.obj.author_id))

        @cached_property
        def reply(self):
            return Permission(UserNeed(self.obj.post.author_id))

        @cached_property
        def delete(self):
            return admin & moderator


    def __init__(self, *args, **kwargs):
        super(Comment, self).__init__(*args, **kwargs)

    def __str__(self):
        return self.comment

    def __repr__(self):
        return "<%s>" % self

    @cached_property
    def permissions(self):
        return self.Permissions(self)

    def _get_author(self):
        if self._author:
            self._author.website = None
            return self._author
        return storage(email = self.email,
                       nickname = self.nickname,
                       website = self.website)

    def _set_author(self, author):
        self._author = author

    author = db.synonym("_author", descriptor=property(_get_author, _set_author))

    @cached_property
    def url(self):
        return "%s#comment-%s" % (self.post.url, self.id)

    @cached_property
    def markdown(self):
        return markdown(self.comment or '')

    @cached_property
    def json(self):
        return dict(id=self.id,
                    author=self.author,
                    url=self.url,
                    comment=self.comment,
                    created_date=self.created_date)

    @cached_property
    def item(self):
        return storage(self.json)
示例#8
0
class User(db.Model):

    __tablename__ = 'users'

    query_class = UserQuery

    PER_PAGE = 50
    TWEET_PER_PAGE = 30

    MEMBER = 100
    MODERATOR = 200
    ADMIN = 300

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True)
    nickname = db.Column(db.String(20))
    email = db.Column(db.String(100), unique=True, nullable=False)
    _password = db.Column("password", db.String(80), nullable=False)
    role = db.Column(db.Integer, default=MEMBER)
    activation_key = db.Column(db.String(40))
    date_joined = db.Column(db.DateTime, default=datetime.utcnow)
    last_login = db.Column(db.DateTime, default=datetime.utcnow)
    block = db.Column(db.Boolean, default=False)

    class Permissions(object):
        def __init__(self, obj):
            self.obj = obj

        @cached_property
        def edit(self):
            return Permission(UserNeed(self.obj.id)) & admin

    def __init__(self, *args, **kwargs):
        super(User, self).__init__(*args, **kwargs)

    def __str__(self):
        return "User: %s" % self.nickname

    def __repr__(self):
        return "<%s>" % self

    @cached_property
    def permissions(self):
        return self.Permissions(self)

    @cached_property
    def provides(self):
        needs = [RoleNeed('authenticated'), UserNeed(self.id)]

        if self.is_moderator:
            needs.append(RoleNeed('moderator'))

        if self.is_admin:
            needs.append(RoleNeed('admin'))

        return needs

    def _get_password(self):
        return self._password

    def _set_password(self, password):
        self._password = hashlib.md5(password).hexdigest()

    password = db.synonym("_password",
                          descriptor=property(_get_password, _set_password))

    def check_password(self, password):
        if self.password is None:
            return False
        return self.password == hashlib.md5(password).hexdigest()

    @property
    def is_moderator(self):
        return self.role >= self.MODERATOR

    @property
    def is_admin(self):
        return self.role >= self.ADMIN

    @property
    def json(self):
        return dict(id=self.id,
                    username=self.username,
                    nickname=self.nickname,
                    email=self.email,
                    is_admin=self.is_admin,
                    is_moderator=self.is_moderator,
                    last_login=self.last_login)