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', backref='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, u'公开'), (1, u'隐藏')] def __repr__(self): return '<ArticleTypeSetting %r>' % self.name
class Menu(db.Model): __tablename__ = 'menus' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) types = db.relationship('ArticleType', backref='menu', lazy='dynamic') order = db.Column(db.Integer, default=0, nullable=False) 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 = [u'Web开发', u'数据库', u'网络技术', u'爱生活,爱自己', u'Linux世界', u'开发语言'] 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, u'不选择导航(该分类将单独成一导航)')) return menus def __repr__(self): return '<Menu %r>' % self.name
class Follow(db.Model): __tablename__ = 'follows' 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)
class Log(BaseModel): """用户对于物品的操作记录(购买,查看,评价等)""" eventId = db.Column("event_id", db.Integer, db.ForeignKey("event.id"), nullable=False, comment="事件名称") itemId = db.Column("item_id", db.Integer, nullable=False, comment="物品ID") userId = db.Column("user_id", db.Integer, nullable=False, comment="用户ID")
class User(BaseModel): """用户""" userName = db.Column("user_name", db.String(128), comment="用户名", nullable=True) userId = db.Column("user_id", db.Integer, comment="用户ID") def __init__(self, user_name, user_id): self.userName = user_name self.userId = user_id
class ChromePlugin(db.Model): __tablename__ = 'chrome_plugin' id = db.Column(db.Integer, primary_key=True) plugin_id = db.Column(db.String(128)) name = db.Column(db.String(256)) short_desc = db.Column(db.Text) description = db.Column(db.Text) cover_image = db.Column(db.String(512)) image_group = db.Column(db.Text) crx_url = db.Column(db.String(512)) create_time = db.Column(db.DateTime, index=True, default=datetime.utcnow) update_time = db.Column(db.DateTime, index=True, default=datetime.utcnow)
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) articles = db.relationship('Article', backref='articleType', lazy='dynamic') menu_id = db.Column(db.Integer, db.ForeignKey('menus.id'), default=None) setting_id = db.Column(db.Integer, db.ForeignKey('articleTypeSettings.id')) @staticmethod def insert_system_articleType(): articleType = ArticleType( name=u'未分类', introduction=u'系统默认分类,不可删除。', 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', u'Linux成长之路', u'Linux运维实战', u'其它', u'思科网络技术', u'生活那些事', u'学校那些事', u'感情那些事', '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 # if the articleType does not have setting, # its is_hie and is_protected property will be False. def __repr__(self): return '<Type %r>' % self.name
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=u'开源博客系统Blog_mini', signature=u'让每个人都轻松拥有可管理的个人博客!— By xpleaf', navbar='inverse') db.session.add(blog_mini_info) db.session.commit()
class Article(db.Model): __tablename__ = 'articles' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(256), unique=True) ref_url = db.Column(db.String(256), 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', backref='article', lazy='dynamic') @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
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()
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', backref='source', lazy='dynamic') @staticmethod def insert_sources(): sources = (u'原创', u'转载', u'翻译') 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
class Ratings(BaseModel): """ 用户评分数据 """ rating = db.Column("rating", db.String(16), nullable=False, comment="评分") itemId = db.Column("item_id", db.Integer, nullable=False, comment="物品ID") userId = db.Column("user_id", db.Integer, nullable=False, comment="用户ID") rating_timestamp = db.Column("rating_timestamp", db.DateTime, comment="时间戳") type = db.Column("type", db.String(32), default="implicit", comment="类型:显式/隐式") def __init__(self, **kwargs): self.rating = kwargs['rating'] self.itemId = kwargs['itemId'] self.userId = kwargs['userId'] self.rating_timestamp = kwargs['rating_timestamp'] self.type = kwargs['type']
class User(UserMixin, db.Model): 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): raise AttributeError('password is not a readable attribute') @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(User, self).__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)
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=u'博客统计', note=u'系统插件', 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
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], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') def __init__(self, **kwargs): super(Comment, self).__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
class AssociationRule(BaseModel): """ 1.规则的生成与获取(查询)应当分离开来,为保证生成与查询过程没有数据冲突,可对数据进行版本控制。 """ source = db.Column(db.Integer, comment="关联源商品") target = db.Column(db.Integer, comment="关联目标商品") support = db.Column(db.Float(6), comment="关联组合出现的次数与所有订单数量的比") confidence = db.Column(db.Float(6), comment="关联组合商品出现次数与关联源商品单独出现次数的比") def generate_transaction(self): sql_str = "select sku_id,order_no from catering_task order by order_no,sku_id" tasks = db.session.execute(sql_str).fetchall() transactions = dict() for task in tasks: order_no = task['order_no'] sku_id = task['sku_id'] if order_no not in transactions: transactions[order_no] = [] transactions[order_no].append(sku_id) return transactions def calculate_itemsets_one(self, transactions, min_sup=0.01): N = len(transactions) temp = defaultdict(int) one_itemsets = dict() for key, items in transactions.items(): for item in items: inx = frozenset({item}) temp[inx] += 1 for key, itemset in temp.items(): if itemset > N * min_sup: one_itemsets[key] = itemset return one_itemsets def has_support(self, perm, one_itemsets): return frozenset({perm[0]}) in one_itemsets and frozenset( {perm[1]}) in one_itemsets def calculate_itemsets_two(self, transactions, one_itemsets, min_sup=0.01): two_itemsets = defaultdict(int) for key, items in transactions.items(): items = list(set(items)) if len(items) > 2: for perm in combinations(items, 2): if self.has_support(perm, one_itemsets): two_itemsets[frozenset(perm)] += 1 elif len(items) == 2: if self.has_support(items, one_itemsets): two_itemsets[frozenset(items)] += 1 return two_itemsets def calculate_association_rules(self, one_itemsets, two_itemsets, N): timestamp = datetime.now() db.seesion.execute("truncate association_rule") rules = [] for source, source_freq in one_itemsets.items(): for key, group_freq in two_itemsets.items(): if source.issubset(key): target = key.difference(source) support = group_freq / N confidence = group_freq / source_freq rules.append((timestamp, next(iter(source)), next(iter(target)), confidence, support)) rule = AssociationRule() rule.target = next(iter(target)) rule.source = next(iter(source)) rule.confidence = confidence rule.support = support db.session.add(rule) db.session.commit() return rules def calculate_support_confidence(self, transactions, min_sup=0.01): N = len(transactions) one_itemsets = self.calculate_itemsets_one(transactions, min_sup) two_itemsets = self.calculate_itemsets_two(transactions, one_itemsets, min_sup) rules = self.calculate_association_rules(one_itemsets, two_itemsets, N) return rules
class Event(BaseModel): eventName = db.Column(db.String(128), nullable=False, comment="事件名称") event_name = db.relationship('Log', backref='event', lazy=True)
class Item(BaseModel): """内容/物品""" itemName = db.Column("item_name", db.String(128), comment="内容名称") itemCode = db.column("item_code", db.String(64), comment="内容编码")