示例#1
0
class ArticleTypeSetting(db.Model):
    __tablename__ = 'articleTypeSettings'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    protected = db.Column(db.Boolean, default=False)
    hide = db.Column(db.Boolean, default=False)
    types = db.relationship('ArticleType', back_populates='setting', lazy='dynamic')

    @staticmethod
    def insert_system_setting():
        system = ArticleTypeSetting(name='system', protected=True, hide=True)
        db.session.add(system)
        db.session.commit()

    @staticmethod
    def insert_default_settings():
        system_setting = ArticleTypeSetting(name='system', protected=True, hide=True)
        common_setting = ArticleTypeSetting(name='common', protected=False, hide=False)
        db.session.add(system_setting)
        db.session.add(common_setting)
        db.session.commit()

    @staticmethod
    def return_setting_hide():
        return [(2, '公开'), (1, '隐藏')]

    def __repr__(self):
        return '<ArticleTypeSetting %r>' % self.name
示例#2
0
class Menu(db.Model):
    __tablename__ = 'menus'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    order = db.Column(db.Integer, default=0, nullable=False)
    types = db.relationship('ArticleType',back_populates='menu',lazy='dynamic')

    def sort_delete(self):
        for menu in Menu.query.order_by(Menu.order).offset(self.order).all():
            menu.order -= 1
            db.session.add(menu)


    @staticmethod
    def insert_menus():
        menus = ['Web开发', '数据库', '网络技术', '爱生活,爱自己',
                 'Linux世界', '开发语言']
        for name in menus:
            menu = Menu(name = name)
            db.session.add(menu)
            db.session.commit()
            menu.order = menu.id
            db.session.add(menu) #这行可以不要,直接提交也可以
            db.session.commit()

    @staticmethod
    def return_menus():
        menus = [(m.id,m.name) for m in Menu.query.all()]
        menus.append(-1,'不选择导航(该分类将单独成一导航)')
        return menus

    def __repr__(self):
        return '<Menu %r>' % self.name
示例#3
0
class Follow(db.Model):
    __tablename__ = 'Follow'
    follower_id = db.Column(db.Integer,db.ForeignKey('comments.id'),
                           primary_key= True)
    followed_id = db.Column(db.Integer,db.ForeignKey('comments.id'),
                           primary_key= True)
    follower = db.relationship('Comment',foreign_keys = [follower_id],back_populates='followed',lazy='joined')
    followed = db.relationship('Comment',foreign_keys = [followed_id],back_populates='followers',lazy='joined')
示例#4
0
class BlogInfo(db.Model):
    __tablename__ = 'blog_info'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(64))
    signature = db.Column(db.Text)
    navbar = db.Column(db.String(64))

    @staticmethod
    def insert_blog_info():
        blog_mini_info = BlogInfo(title='开源博客系统Blog_mini',
                                  signature='让每个人都轻松拥有可管理的个人博客!— By xpleaf',
                                  navbar='inverse')
        db.session.add(blog_mini_info)
        db.session.commit()
示例#5
0
class ArticleType(db.Model):
    __tablename__ = 'articleTypes'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    introduction = db.Column(db.Text, default=None)
    menu_id = db.Column(db.Integer, db.ForeignKey('menus.id'), default=None)
    setting_id = db.Column(db.Integer, db.ForeignKey('articleTypeSettings.id'))

    menu = db.relationship('Menu', back_populates='types')
    articles = db.relationship('Article', back_populates='articleType', lazy='dynamic')
    setting = db.relationship('ArticleTypeSetting',back_populates='types')

    @staticmethod
    def insert_system_articleType():
        articleType = ArticleType(name='未分类',
                                  introduction='系统默认分类,不可删除。',
                                  setting=ArticleTypeSetting.query.filter_by(protected=True).first()  # 可以这样设置多对一关系
                                  )
        db.session.add(articleType)
        db.session.commit()

    @staticmethod
    def insert_articleTypes():
        articleTypes = ['Python', 'Java', 'JavaScript', 'Django',
                        'CentOS', 'Ubuntu', 'MySQL', 'Redis',
                        'Linux成长之路', 'Linux运维实战', '其它',
                        '思科网络技术', '生活那些事', '学校那些事',
                        '感情那些事', 'Flask']
        for name in articleTypes:
            articleType = ArticleType(name=name,
                                      setting=ArticleTypeSetting(name=name))
            db.session.add(articleType)
        db.session.commit()

    @property
    def is_protected(self):
        if self.setting:
            return self.setting.protected
        else:
            return False

    @property
    def is_hide(self):
        if self.setting:
            return self.setting.hide
        else:
            return False

    def __repr__(self):
        return '<Type %r>' % self.name
示例#6
0
class BlogView(db.Model):
    __tablename__ = 'blog_view'
    id = db.Column(db.Integer, primary_key=True)
    num_of_view = db.Column(db.BigInteger, default=0)

    @staticmethod
    def insert_view():
        view = BlogView(num_of_view=0)
        db.session.add(view)
        db.session.commit()

    @staticmethod
    def add_view(db):
        view = BlogView.query.first()
        view.num_of_view += 1
        db.session.add(view)
        db.session.commit()
示例#7
0
class User(db.Model,UserMixin):
    id = db.Column(db.Integer,primary_key=True)
    email =  db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    avatar_hash = db.Column(db.String(32))

    @staticmethod
    def insert_admin(email,username,password):
        user = User(email=email, username=username, password=password)
        db.session.add(user)
        db.session.commit()

    @property
    def password(self):
        """
        密码属性不可被访问
        """
        return AttributeError('密码不可访问')

    @password.setter
    def password(self,password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self,password):
        return check_password_hash(self.password_hash,password)


    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        if self.email is not None and self.avatar_hash is None:
            self.avatar_hash = hashlib.md5(self.email.encode('utf-8')).hexdigest()

    def gravatar(self,size=40,default='identicon',rating='g'):
        # if request.is_secure:
        #     url = 'https://secure.gravatar.com/avatar'
        # else:
        #     url = 'http://www.gravatar.com/avatar'
        url = 'https://gravatar.loli.net/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating)
示例#8
0
class Source(db.Model):
    __tablename__ = 'sources'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    articles = db.relationship('Article', back_populates='source', lazy='dynamic')

    @staticmethod
    def insert_sources():
        sources = ('原创',
                   '转载',
                   '翻译')
        for s in sources:
            source = Source.query.filter_by(name=s).first()
            if source is None:
                source = Source(name=s)
            db.session.add(source)
        db.session.commit()

    def __repr__(self):
        return '<Source %r>' % self.name
示例#9
0
class Article(db.Model):
    __tablename__ = 'articles'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(64), unique=True)
    content = db.Column(db.Text)
    summary = db.Column(db.Text)
    create_time = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    update_time = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    num_of_view = db.Column(db.Integer, default=0)
    articleType_id = db.Column(db.Integer, db.ForeignKey('articleTypes.id'))
    source_id = db.Column(db.Integer, db.ForeignKey('sources.id'))
    comments = db.relationship('Comment', back_populates='article', lazy='dynamic')
    articleType = db.relationship('ArticleType',back_populates='articles',)
    source = db.relationship('Source',back_populates='articles')

    @staticmethod
    def generate_fake(count=100):
        from sqlalchemy.exc import IntegrityError
        from random import seed, randint
        import forgery_py

        seed()
        articleType_count = ArticleType.query.count()
        source_count = Source.query.count()
        for i in range(count):
            aT = ArticleType.query.offset(randint(0, articleType_count - 1)).first()
            s = Source.query.offset(randint(0, source_count - 1)).first()
            a = Article(title=forgery_py.lorem_ipsum.title(randint(3, 5)),
                        content=forgery_py.lorem_ipsum.sentences(randint(15, 35)),
                        summary=forgery_py.lorem_ipsum.sentences(randint(2, 5)),
                        num_of_view=randint(100, 15000),
                        articleType=aT, source=s)
            db.session.add(a)
            try:
                db.session.commit()
            except IntegrityError:
                db.session.rollback()

    @staticmethod
    def add_view(article, db):
        article.num_of_view += 1
        db.session.add(article)
        db.session.commit()

    def __repr__(self):
        return '<Article %r>' % self.title
示例#10
0
class Plugin(db.Model):
    __tablename__ = 'plugins'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(64), unique=True)
    note = db.Column(db.Text, default='')
    content = db.Column(db.Text, default='')
    order = db.Column(db.Integer, default=0)
    disabled = db.Column(db.Boolean, default=False)

    @staticmethod
    def insert_system_plugin():
        plugin = Plugin(title='博客统计',
                        note='系统插件',
                        content='system_plugin',
                        order=1)
        db.session.add(plugin)
        db.session.commit()

    def sort_delete(self):
        for plugin in Plugin.query.order_by(Plugin.order.asc()).offset(self.order).all():
            plugin.order -= 1
            db.session.add(plugin)

    def __repr__(self):
        return '<Plugin %r>' % self.title
示例#11
0
class Comment(db.Model):
    __tablename__ = 'comments'
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    author_name = db.Column(db.String(64))
    author_email = db.Column(db.String(64))
    avatar_hash = db.Column(db.String(32))
    article_id = db.Column(db.Integer, db.ForeignKey('articles.id'))
    disabled = db.Column(db.Boolean, default=False)
    comment_type = db.Column(db.String(64), default='comment')
    reply_to = db.Column(db.String(128), default='notReply')

    followed = db.relationship('Follow',
                               foreign_keys=[Follow.follower_id],
                               back_populates = 'follower',
                               lazy = 'dynamic',
                               cascade = 'all')
    followers = db.relationship('Follow',
                               foreign_keys=[Follow.followed_id],
                               back_populates = 'followed',
                               lazy = 'dynamic',
                               cascade = 'all')

    article = db.relationship('Article',back_populates = 'comments')

    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        if self.author_email is not None and self.avatar_hash is None:
            self.avatar_hash = hashlib.md5(self.author_email.encode('utf-8')).hexdigest()

    def gravatar(self, size=40, default='identicon', rating='g'):
        # if request.is_secure:
        #     url = 'https://secure.gravatar.com/avatar'
        # else:
        #     url = 'http://www.gravatar.com/avatar'
        url = 'https://gravatar.loli.net/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.author_email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating)

    @staticmethod
    def generate_fake(count=100):
        from random import seed, randint
        import forgery_py

        seed()
        article_count = Article.query.count()
        for i in range(count):
            a = Article.query.offset(randint(0, article_count - 1)).first()
            c = Comment(content=forgery_py.lorem_ipsum.sentences(randint(3, 5)),
                        timestamp=forgery_py.date.date(True),
                        author_name=forgery_py.internet.user_name(True),
                        author_email=forgery_py.internet.email_address(),
                        article=a)
            db.session.add(c)
        try:
            db.session.commit()
        except:
            db.session.rollback()

    @staticmethod
    def generate_fake_replies(count=100):
        from random import seed, randint
        import forgery_py

        seed()
        comment_count = Comment.query.count()
        for i in range(count):
            followed = Comment.query.offset(randint(0, comment_count - 1)).first()
            c = Comment(content=forgery_py.lorem_ipsum.sentences(randint(3, 5)),
                        timestamp=forgery_py.date.date(True),
                        author_name=forgery_py.internet.user_name(True),
                        author_email=forgery_py.internet.email_address(),
                        article=followed.article, comment_type='reply',
                        reply_to=followed.author_name)
            f = Follow(follower=c, followed=followed)
            db.session.add(f)
            db.session.commit()

    def is_reply(self):
        if self.followed.count() == 0:
            return False
        else:
            return True

    # to confirm whether the comment is a reply or not

    def followed_name(self):
        if self.is_reply():
            return self.followed.first().followed.author_name