from app.extensions import db class Goods(db.Model): __tablename__ = 'goods' id = db.Column(db.Integer,primary_key=True) goodname = db.Column(db.String) goodprice = db.Column(db.Float) icon = db.Column(db.String(128)) content = db.Column(db.Text) viemcount = db.Column(db.Integer,default=0) # 多对多的关联表创建 collect = db.Table( 'collect_table', db.Column('good_id', db.Integer, db.ForeignKey('goods.id')), db.Column('user_id', db.Integer, db.ForeignKey('users.id')), )
url_for(endpoint, page=page, per_page=per_page, **kwargs), 'next': url_for(endpoint, page=page + 1, per_page=per_page, **kwargs) if resources.has_next else None, 'prev': url_for(endpoint, page=page - 1, per_page=per_page, **kwargs) if resources.has_prev else None } } return data # 粉丝关注他人 followers = db.Table( 'followers', db.Column('follower_id', db.Integer, db.ForeignKey('users.id')), db.Column('followed_id', db.Integer, db.ForeignKey('users.id')), db.Column('timestamp', db.DateTime, default=datetime.utcnow)) # 评论点赞 comments_likes = db.Table( 'comments_likes', db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('comment_id', db.Integer, db.ForeignKey('comments.id')), db.Column('timestamp', db.DateTime, default=datetime.utcnow)) # 黑名单(user_id 屏蔽 block_id) blacklist = db.Table( 'blacklist', db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('block_id', db.Integer, db.ForeignKey('users.id')), db.Column('timestamp', db.DateTime, default=datetime.utcnow))
# 添加收藏 def add_favorite(self, pid): p = Posts.query.get(pid) self.favorites.append(p) #取消收藏 def del_favorite(self, pid): p = Posts.query.get(pid) self.favorites.remove(p) # 该装饰器其实就是一个回调函数 @login_manager.user_loader def loader_user(uid): return User.query.get(uid) class Posts(db.Model): id = db.Column(db.Integer, primary_key=True) # 内部关联 rid = db.Column(db.Integer, index=True, default=0) content = db.Column(db.Text) timestamp = db.Column(db.DateTime, default=datetime.utcnow) uid = db.Column(db.Integer, db.ForeignKey("user.id")) # 用户收藏博客关联模型 collections = db.Table( 'collections', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('posts_id', db.Integer, db.ForeignKey('posts.id')))
'self': url_for(endpoint, page=page, per_page=per_page, **kwargs), 'next': url_for(endpoint, page=page + 1, per_page=per_page, **kwargs) if resources.has_next else None, 'prev': url_for(endpoint, page=page - 1, per_page=per_page, **kwargs) if resources.has_prev else None } } return data # 关注他人 暂时不用 followers = db.Table('followers', Column('follower_id', Integer, ForeignKey('users.id')), Column('followed_id', Integer, ForeignKey('users.id')), Column('timestamp', DateTime, default=datetime.utcnow)) # 评论点赞 暂时也不用 comments_likes = db.Table( 'comments_likes', Column('user_id', Integer, ForeignKey('users.id')), Column('comment_id', Integer, ForeignKey('comments.id')), Column('timestamp', DateTime, default=datetime.utcnow)) # 评论发布 posts_likes = db.Table('posts_likes', Column('user_id', Integer, ForeignKey('users.id')), Column('post_id', Integer, ForeignKey('posts.id')), Column('timestamp', DateTime, default=datetime.utcnow))
# -*- coding: utf-8 -*- import os from datetime import datetime from flask import current_app from flask_login import UserMixin from flask_avatars import Identicon from app.extensions import db from werkzeug.security import generate_password_hash, check_password_hash """ 角色权限中间表 """ roles_permissions = db.Table('roles_permissions', db.Column('role_id', db.Integer, db.ForeignKey('role.id')), db.Column('permission_id', db.Integer, db.ForeignKey('permission.id')) ) """ 用户模型 """ class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, index=True) email = db.Column(db.String(254), unique=True, index=True) password_hash = db.Column(db.String(128)) name = db.Column(db.String(30)) website = db.Column(db.String(255)) bio = db.Column(db.String(120)) location = db.Column(db.String(50)) member_since = db.Column(db.DateTime, default=datetime.now) confirmed = db.Column(db.Boolean, default=False) # 确认用户状态是否激活 avatar_s = db.Column(db.String(64)) avatar_m = db.Column(db.String(64))
# -*- coding: utf-8 -*- """ Base models """ from flask_security import RoleMixin, UserMixin from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound from app.extensions import db from lib.model_utils import GetOr404Mixin, GetOrCreateMixin user_roles = db.Table( 'user_roles', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('role_id', db.Integer, db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin, GetOrCreateMixin, GetOr404Mixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String) full_name = db.Column(db.String) inbox_email = db.Column(db.String(255), unique=True) active = db.Column(db.Boolean) confirmed_at = db.Column(db.DateTime) roles = db.relationship('Role',
class Profile(db.Model): id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(255)) last_name = db.Column(db.String(255)) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', back_populates='profile') def __repr__(self): return '<Profile {}>'.format(self.user_id, self.first_name, self.last_name) # FANTASYTEAM and PLAYER relationship Many to Many fantasy_teams_players = db.Table('association', db.Column('fantasy_team_id', db.Integer, ForeignKey('fantasy_team.id')), db.Column('player_id', db.Integer, ForeignKey('player.id')) ) class FantasyTeam(db.Model): __tablename__ = 'fantasy_team' id = db.Column(db.Integer, primary_key=True) players = db.relationship("Player", secondary=fantasy_teams_players, back_populates="fantasy_teams") name = db.Column(db.String(255)) # USER relationship 1 to 1 user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', back_populates='fantasy_team')
import os from datetime import datetime from flask import current_app from flask_login import UserMixin from flask_avatars import Identicon from werkzeug.security import generate_password_hash, check_password_hash from app.extensions import db, whooshee roles_permissions = db.Table( 'roles_permissions', db.Column('role_id', db.Integer, db.ForeignKey('role.id')), db.Column('permission_id', db.Integer, db.ForeignKey('permission.id'))) class Collect(db.Model): collect_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) collected_id = db.Column(db.Integer, db.ForeignKey('photo.id'), primary_key=True) timestamp = db.Column(db.DateTime, default=datetime.utcnow) collector = db.relationship('User', back_populates='collections', lazy='joined') collected = db.relationship('Photo', back_populates='collectors', lazy='joined') class Permission(db.Model): id = db.Column(db.Integer, primary_key=True)
from app.extensions import db from app.models.extensions import BaseExtension from app.models.source_data import SourceData from sqlalchemy.dialects import postgresql from fhirclient.models import valueset, codesystem from fhirclient.models.fhirabstractbase import FHIRValidationError ################################################################################################## # SOURCE_DATA -> CODESYSTEM ASSOCIATION TABLE ################################################################################################## source_data_codesystem = db.Table( 'source_data_codesystem', db.Column('source_data_id', db.Integer, db.ForeignKey('source_data.id'), primary_key=True), db.Column('codesystem_id', db.Integer, db.ForeignKey('codesystem.id'), primary_key=True)) class CodeSystem(db.Model): """Code systems define which codes (symbols and/or expressions) exist, and how they are understood. The CodeSystem resource is used to declare the existence of a code system, and its key properties: 1) Identifying URL and version 2) Description, Copyright, publication date, and other metadata 3) Some key properties of the code system itself - whether it's case sensitive, version safe, and whether it defines a compositional grammar 4) What filters can be used in value sets that use the code system in a ValueSet.compose element
import jwt import sys import json from app.extensions import db from datetime import datetime from hashlib import md5 from flask_login import AnonymousUserMixin, UserMixin from app.extensions import bcrypt, login from app.models.post import Post from app.models.notification import Notification from app.models.user_notification import UserNotification likes = db.Table( 'likes', db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('post_id', db.Integer, db.ForeignKey('posts.id', ondelete='CASCADE'))) followers = db.Table( 'followers', db.Column('follower_id', db.Integer, db.ForeignKey('users.id')), db.Column('followed_id', db.Integer, db.ForeignKey('users.id'))) class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True, nullable=False)
class EventStatus: """Class to represent an event's status.""" LIVE = "live" PAST = "past" DRAFT = "draft" # association table between users and events tables saved_events = db.Table( "saved_events", db.Column("user_id", db.Integer, db.ForeignKey("users.id"), nullable=False), db.Column("event_id", db.Integer, db.ForeignKey("events.id"), nullable=False), db.PrimaryKeyConstraint("user_id", "event_id"), ) class Event(AbstractModel): """Class to represent an event""" __tablename__ = "events" __searchable__ = [ "title", "description", "venue.state", "venue.city",
# user/models/associations.py from app.extensions import db users_roles_association = db.Table( 'users_roles_association', db.metadata, db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('role_id', db.Integer, db.ForeignKey('roles.id')))
from app.extensions import db ################################################################################################## # ROLE -> APP PERMISSION ASSOCIATION TABLE ################################################################################################## role_app_permission = db.Table( 'role_app_permission', db.Column('role_id', db.Integer, db.ForeignKey('role.id'), primary_key=True), db.Column('app_permission_id', db.Integer, db.ForeignKey('app_permission.id'), primary_key=True)) ################################################################################################### # APP PERMISSION SQL ALCHEMY MODEL DEFINITION ################################################################################################### class AppPermission(db.Model): __tablename__ = 'app_permission' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text, unique=True) roles = db.relationship('Role', secondary=role_app_permission, back_populates='app_permissions') def __repr__(self):
class RoleEnum(Enum): ADMIN = 'ADMIN' MANAGER = 'MANAGER' STAFF = 'STAFF' GUEST = 'GUEST' ANONYMOUS = 'ANONYMOUS' ''' Many to many relationship between roles and permissions ''' role_permission = db.Table( 'role_permission', db.Column('role_id', db.Integer, db.ForeignKey('role.id'), nullable=False), db.Column('permission_id', db.Integer, db.ForeignKey('permission.id'), nullable=False), db.PrimaryKeyConstraint('role_id', 'permission_id')) class Role(db.Model): ''' Database representation of a role ''' __tablename__ = 'role' _id = db.Column('id', db.Integer, primary_key=True) _name = db.Column('name', db.String(120), unique=True, nullable=False) _permissions = db.relationship('Permission',
make_searchable() class NoteQuery(BaseQuery, SearchQueryMixin): pass def sanitize(content): soup = BeautifulSoup(content, 'html.parser') nodes = soup.recursiveChildGenerator() text_nodes = [e for e in nodes if isinstance(e, str)] return ''.join(text_nodes) tags = db.Table('note_tag', db.Column('tag.id', db.Integer, db.ForeignKey('tag.id')), db.Column('note.id', db.Integer, db.ForeignKey('note.id'))) class Note(db.Model, GetOr404Mixin, GetOrCreateMixin): query_class = NoteQuery id = db.Column(db.Integer, primary_key=True) content = db.Column(db.Text) created = db.Column(db.DateTime) updated = db.Column(db.DateTime) is_email = db.Column(db.Boolean) history = db.relationship('NoteHistory', backref='note', cascade='delete') user_id = db.Column(db.Integer, db.ForeignKey('user.id')) author = db.relationship('User', backref='notes') search_vector = db.Column(TSVectorType('content'))
# -*- coding: utf-8 -*- from flask import current_app from .user import User from .role import Role from .codes import Codes from .post import Post from app.extensions import db # Define models roles_users = db.Table( 's_roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('s_user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('s_role.id'))) def init_db(): """Clear existing data and create new tables.""" # with current_app.open_resource("schema.sql") as f: # db.executescript(f.read().decode("utf8")) print("初始化数据库脚本文件!!!")
#-*-coding=utf-8-*- # project: workspace # createtime: 2018/4/12 9:09 # IDE: PyCharm # anthor: ZT@gufan from app.extensions import db #定义多对多关系 注意定义一个中间表 posts_tags = db.Table( "posts_tags", db.Column('post_id', db.Integer, db.ForeignKey("posts.id")), db.Column('tag_id', db.Integer, db.ForeignKey('tags.id'))) class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(255), nullable=False) password = db.Column(db.String(255), nullable=False) posts = db.relationship('Post', backref="users", lazy="dynamic") def __repr__(self): return "<Model User {}>".format(self.username) class Post(db.Model): __tablename__ = "posts" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255)) text = db.Column(db.Text())
'id': str(self.id), 'username': self.username, 'avator': self.avator, 'email': self.email, # 'picture':self.picture, # 'comment':self.comment } return json_user # 关联表 relation = db.Table( 'relation', db.Column('tags_id', db.Integer, db.ForeignKey('tags.id'), primary_key=True), db.Column('picture_id', db.Integer, db.ForeignKey('picture.id'), primary_key=True)) class Picture(db.Model): id = db.Column(db.Integer, primary_key=True) despriction = db.Column(db.String(5000), unique=True) address = db.Column(db.String(35), unique=True) userId = db.Column(db.Integer, db.ForeignKey('User.id')) tags = db.relationship('Tags', secondary=relation, backref=db.backref('picture', lazy='dynamic')) commnet = db.relationship('Comments', backref='picture', lazy='dynamic')
return pwd_context.verify(password, self.password) def to_json(self): json_user = { 'id': str(self.id), 'username': self.username, 'avator': self.avator, 'email': self.email, # 'pictures':self.pictures } return json_user # 关联表tag_picture relation = db.Table( 'tag_pic_relation', db.Column('id', db.Integer, primary_key=True), db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')), db.Column('picture_id', db.Integer, db.ForeignKey('pictures.id'))) class Picture(db.Model): __tablename__ = 'pictures' id = db.Column(db.Integer, primary_key=True) despriction = db.Column(db.String(5000), unique=True) address = db.Column(db.String(200), unique=True) userId = db.Column(db.Integer, db.ForeignKey('user.id')) tags = db.relationship('Tag', secondary=relation, backref=db.backref('pictures', lazy='dynamic')) def to_json(self): templist = []
from sqlalchemy.event import listens_for from sqlalchemy.sql import expression from sqlalchemy.ext.compiler import compiles from sqlalchemy.types import DateTime from flask_sqlalchemy import SQLAlchemy from app.extensions import db file_path = os.path.join(os.path.dirname(__file__), 'static/files') term_category_relationship = db.Table('term_category_relationship', db.Column('term_id', db.Integer, db.ForeignKey('term.id'), nullable=False), db.Column('category_id', db.Integer, db.ForeignKey('category.id'), nullable=False), db.PrimaryKeyConstraint('term_id', 'category_id')) document_types_relationship = db.Table('document_types_table', db.Column('document_id', db.Integer, db.ForeignKey('document.id'), nullable=False), db.Column('document_type_id', db.Integer, db.ForeignKey('document_type.id'), nullable=False), db.PrimaryKeyConstraint('document_id', 'document_type_id'))
from datetime import datetime from app.extensions import db, ma from marshmallow_enum import EnumField class priorityEnum(enum.Enum): low, medium, high = "low", "medium", "high" def __str__(self): return self.name task_empl = db.Table( "task_empl", db.Column("task_id", db.Integer, db.ForeignKey("task.id")), db.Column("empl_id", db.Integer, db.ForeignKey("employee.id")), ) class Task(db.Model): id = db.Column(db.Integer(), primary_key=True) title = db.Column(db.String(), nullable=False) description = db.Column(db.String(), nullable=False) created_at = db.Column(db.String(), default=datetime.utcnow()) deadline = db.Column(db.String()) priority = db.Column(db.Enum(priorityEnum), default="high") is_done = db.Column(db.Boolean(), default=False) category_id = db.Column(db.Integer(), db.ForeignKey("category.id")) def __repr__(self):
posts = db.relationship('Post', back_populates='category') tag = db.relationship('Tag', back_populates='category') def delete(self): default_category = Category.query.get(1) posts = self.posts[:] for post in posts: post.category = default_category db.session.delete(self) db.session.commit() #repr()方法显示一个可读字符串,虽然不是完全必要,不过用于调试和测试还是很不错的。 def __repr__(self): return '<Category {}> '.format(self.name) association_table = db.Table('association', db.Column('tag_name', db.String(50), db.ForeignKey('tag.tname')), db.Column('post_name', db.String(50), db.ForeignKey('post.pslug')) ) class Tag(db.Model): __tablename__ = 'tag' tid = db.Column(db.Integer, primary_key=True) tname = db.Column(db.String(50), unique=True) posts = db.relationship('Post', back_populates='tags', secondary=association_table, lazy='dynamic',cascade='save-update, merge, delete') category_name = db.Column(db.String(30), db.ForeignKey('category.cname')) category = db.relationship('Category', back_populates='tag') def delete(self): default_category = Category.query.get(1) posts = self.posts[:] for post in posts: post.category = default_category db.session.delete(self)
def is_administrator(self): return False login_manager.anonymous_user = AnonymousUser @login_manager.user_loader def load_user(user_id): # loads User object by id (Required callback by flask_login) return User.query.get(int(user_id)) has_category = db.Table( 'has_category', db.Column('category_id', db.Integer, db.ForeignKey('categories.id')), db.Column('post_id', db.Integer, db.ForeignKey('posts.id', ondelete='CASCADE'))) class Category(db.Model): __tablename__ = 'categories' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True, index=True) class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(64), unique=True, index=True) body = db.Column(db.Text)
from app.extensions import db from werkzeug.security import check_password_hash UserLectureAssociation = db.Table('userlecture_association', db.Model.metadata, db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('lecture_id', db.Integer, db.ForeignKey('lecture.id')) ) class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) password = db.Column(db.String(1000), nullable=False) display_name= db.Column(db.String(80)) lecture = db.relationship("Lecture", secondary=UserLectureAssociation, back_populates="user") def __init__(self, username, display_name, password): self.username = username self.display_name = display_name self.password = password def __repr__(self): return "<User: {}>".format(self.username) def get(id): return User.query.get(id) def get_id(self): return self.id
from app.extensions import db from .user import User posts_tags = db.Table( 'post_tags', db.metadata, db.Column('post_id', db.Integer, db.ForeignKey('post.id')), db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(128)) content = db.Column(db.Text) created_at = db.Column(db.DateTime) updated_at = db.Column(db.DateTime) user_id = db.Column(db.Integer(), db.ForeignKey(User.id)) user = db.relationship(User, backref='posts') tags = db.relationship('Tag', secondary=posts_tags) def __str__(self): return "{}".format(self.title)
from .users import User from .post import Post from app.extensions import db # 定义多对多的第三张表 # 收藏 collections = db.Table( 'collections', db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True), db.Column('posts_id', db.Integer, db.ForeignKey('posts.id'), primary_key=True))
from _datetime import datetime from sqlalchemy import Column, Integer, Text, DateTime, ForeignKey from app.extensions import db user_posts = db.Table( 'user_post', Column('user_id',Integer,db.ForeignKey('users.id')), Column('post_id',Integer,db.ForeignKey('posts.id')), ) class Post(db.Model): __tablename__='posts' id = Column(Integer,primary_key=True) rid = Column(Integer,index=True,default=0) title = Column(Text) content = Column(Text) click = Column(Integer,default=0) timestamp = Column(DateTime,default=datetime.utcnow) users = db.relationship('User',backref = 'posts',secondary = user_posts,lazy='dynamic') uid = db.Column(Integer,ForeignKey('users.id'))
""" app.users.models.followers ~~~~~~~~~~~~~~~~~~~~~~~~~~ Followers model. """ from datetime import datetime from app.extensions import db followers = db.Table( 'followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('followed_id', db.Integer, db.ForeignKey('user.id')), db.Column('created', db.DateTime, default=datetime.utcnow))
import uuid from datetime import datetime from app.extensions import db tags = db.Table( 'article_tag', db.Column('tag_id', db.String(64), db.ForeignKey('tag.tag_id')), db.Column('article_id', db.String(64), db.ForeignKey('article.article_id')) ) class Article(db.Model): article_id = db.Column(db.String(64), primary_key=True) article_title = db.Column(db.String(255)) article_url = db.Column(db.String(255)) article_desc = db.Column(db.Text) article_content = db.Column(db.Text) site_id = db.Column(db.String(64), db.ForeignKey('web_site.site_id')) tags = db.relationship('Tag', secondary=tags, backref=db.backref('articles', lazy='dynamic')) create_time = db.Column(db.DateTime) def __init__(self, article_title='', article_url='', article_desc='', article_content='', site_id=None, *args, **kwargs): super(Article, self).__init__(*args, **kwargs) self.article_id = str(uuid.uuid4()) self.article_title = article_title self.article_url = article_url self.article_desc = article_desc self.article_content = article_content self.site_id = site_id
from app.extensions import db from datetime import datetime, timedelta from hashlib import md5 from time import time from flask import current_app from flask_login import UserMixin from app.extensions import bcrypt, login from app.models.post import Post from app.models.message import Message from app.models.notification import Notification import json import jwt followers = db.Table( 'followers', db.Column('follower_id', db.Integer, db.ForeignKey('users.id')), db.Column('followed_id', db.Integer, db.ForeignKey('users.id'))) class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True, nullable=False) email = db.Column(db.String(120), index=True, unique=True, nullable=False) password = db.Column(db.Binary(128), nullable=True) about_me = db.Column(db.String(140)) last_seen = db.Column(db.DateTime, default=datetime.utcnow)