class pro_art(db.Model): __tablename__ = 'pro_art' id = db.Column(db.INTEGER, primary_key=True) name = db.Column(db.TEXT) article_list = db.Column(db.TEXT) @staticmethod def get_article_list(id): """ 返回专家对应的所有论文的列表 :param id: :return: """ info = pro_art.query.filter_by(id=id).first() art_contents = [] list_str = info.article_list.strip() if list_str: lists = list_str.split(',') for list in lists: if list: art_contents.append(articles.give_article(list)) # for content in art_contents: # print content return art_contents
class Produto(Model): empresa_id = db.Column(db.Integer, db.ForeignKey('empresa.id'), nullable=False) nome = db.Column(db.String(length=200)) empresa = db.relationship('Empresa')
class Client(BaseModelMixin, db.Model): """A Client is either a browser or an API device. It represents a session but can be thought of as a device, as the cookie or API key wouldn't be reset unless action is taken. """ # Set to false on logged out. is_active = db.Column(db.Boolean, nullable=False, default=True) client_key = db.Column(db.Text, nullable=False, unique=True) user_id = db.Column(db.Integer, ForeignKey('user.id'), nullable=False) @classmethod def create_with_credentials(cls, email, password, client_key): from flaskapp.models.user import User user_with_email = User.query.filter_by(email=email).first() if user_with_email.hashed_pw_matches_plaintext(password): authenticated_user = user_with_email # What if this user is signing into another account? existing_client = Client.query.filter_by( client_key=client_key).filter_by(is_active=True).first() if existing_client: existing_client.user_id = authenticated_user.id returned_client = existing_client else: new_client = cls(client_key=client_key, user_id=authenticated_user.id) returned_client = new_client db.session.add(returned_client) db.session.commit() return returned_client
class Avator(db.Model): __tablename__ = 'avator' id = db.Column(db.INTEGER, primary_key=True) img = db.Column(db.BLOB) def __repr__(self): return 'info_img:{}'.format(self.id) @staticmethod # 根据id获取头像信息 def get_avator(id, path): """ 根据id来获取对应专家的头像 当数据据和缓存都没有时候,默认给一个空白头像 :param id: 专家的id :param path: 存放头像缓存的路径,默认路径为'path/interface/avator' :return: 返回头像的对应的路径 """ # 为头像缓存添加路径 if not os.path.exists(path): os.mkdir(path) # 调用时返回的是调用函数的路径 # root = os.getcwd() # print 'root', root # 头像缓存在get_avator中,如果存在就无需从数据库中获取了(以id.jpg的方式缓存) img_name = str(id) + '.jpg' avator_path = os.path.join(path, img_name) # print 'avator_path', avator_path if os.path.exists(avator_path): print img_name + ' is existed' return img_name # 缓存中没有,从数据库中获取 else: try: img = Avator.query.filter_by(id=id).first().img avator = open(avator_path, 'wb') avator.write(img) avator.close() print 'get avator: ', img_name return img_name except: print 'cant find avator, plz give a blank one' return 'blank.jpg' @staticmethod def init_avator(): info = Basic_info.query.filter(Basic_info.id >= 0).all() for data in info: Avator.get_avator(data.id, 'flaskapp/static/order/avator/')
class Model(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True, nullable=False) data_de_criacao = db.Column(db.DateTime, nullable=False) ultima_alteracao = db.Column(db.DateTime, nullable=False) @declared_attr def __tablename__(cls): return cls.__name__.lower() def __repr__(self): return f'{self.__tablename__}(id={self.id})'
class Pedido(Model): empresa_id = db.Column(db.Integer, db.ForeignKey('empresa.id'), nullable=False) cliente_id = db.Column(db.Integer, db.ForeignKey('cliente.id'), nullable=True) numero = db.Column(db.Integer) data_de_emissao = db.Column(db.DateTime) total = db.Column(db.Numeric(precision=21, scale=6)) empresa = db.relationship('Empresa') cliente = db.relationship('Cliente') itens = db.relationship('ItemDoPedido', back_populates='pedido')
class ActivatorToken(db.Model, BaseModelMixin): """ This is a device for linking a user to an email address. An activator is an EXPIRING* * The expiring nature of the Activator is the whole reason it's still secure. It's safe to assume that the user wants this. These can either be used for (1) Password Resets (2) First time setup They can be sent via SMS and Email TODO: could factor this out into different subclasses using enums. Could allow SMS to be validated this way too. """ function = db.Column(db.Text, nullable=False, unique=False) activator_code = db.Column(db.Text, nullable=False, unique=True) # Set to false after used or a new one created is_active = db.Column(db.Boolean, nullable=False, default=True) user_id = db.Column(db.Integer, ForeignKey('user.id'), nullable=False) def __init__(self, function, user_id): self.function = function self.user_id = user_id self.activator_code = token_urlsafe(32) def is_expired(self): return (datetime.utcnow() - self.timestamp).days > 2 @classmethod def activator_token_for_user(cls, user, function): exisiting_valid_tokens = cls.query.filter_by(user_id=user.id)\ .filter_by(is_active=True)\ .all() if exisiting_valid_tokens: for token in exisiting_valid_tokens: token.is_active = False db.session.add_all(exisiting_valid_tokens) db.session.commit() new_token = cls(function=function, user_id=user.id) db.session.add(new_token) db.session.commit() return new_token
class articles(db.Model): __tablename__ = 'articles' id = db.Column(db.INTEGER, primary_key=True) title = db.Column(db.TEXT) key_word = db.Column(db.TEXT) abstract = db.Column(db.TEXT) author = db.Column(db.TEXT) journal = db.Column(db.TEXT) @staticmethod def get_article(id): info = articles.query.filter_by(id=id).first() title = info.title key_word = info.key_word abstract = info.abstract author = info.author journal = info.journal return title, key_word, abstract, author, journal @staticmethod def give_article(id): """ 给出一个论文的字符串数据 :param id: :return: """ title, key_word, abstract, author, journal = articles.get_article(id) return title + '. ' + author + '. ' + journal
class ItemDoPedido(Model): empresa_id = db.Column(db.Integer, db.ForeignKey('empresa.id'), nullable=False) pedido_id = db.Column(db.Integer, db.ForeignKey('pedido.id'), nullable=False) produto_id = db.Column(db.Integer, db.ForeignKey('produto.id'), nullable=False) preco_de_tabela = db.Column(db.Numeric(precision=21, scale=6)) preco_liquido = db.Column(db.Numeric(precision=21, scale=6)) quantidade = db.Column(db.Numeric(precision=21, scale=6)) total = db.Column(db.Numeric(precision=21, scale=6)) empresa = db.relationship('Empresa') pedido = db.relationship('Pedido', back_populates='itens') produto = db.relationship('Produto')
class Details(db.Model): __tablename__ = 'details' id = db.Column(db.INTEGER, primary_key=True) name = db.Column(db.TEXT) college = db.Column(db.TEXT) career = db.Column(db.TEXT) contribute = db.Column(db.TEXT) job = db.Column(db.TEXT) @staticmethod def get_details(id): try: pro = Details.query.filter_by(id=id).first() career = pro.career.split('。') contribute = pro.contribute.split('。') job = pro.job.split('。') return career, contribute, job except Exception as e: print e
class Empresa(Model): nome = db.Column(db.String(length=200))
class Lab_Form(db.Model): __tablename__ = 'info_lab' __analyzer__ = ChineseAnalyzer() id = db.Column(db.INTEGER, primary_key=True) lab_name = db.Column(db.TEXT) lab_school = db.Column(db.TEXT) lab_introduction = db.Column(db.TEXT) lab_location = db.Column(db.TEXT) lab_postcode = db.Column(db.TEXT) lab_supportunit = db.Column(db.TEXT) lab_tel = db.Column(db.TEXT) lab_fax = db.Column(db.TEXT) lab_mail = db.Column(db.TEXT) lab_url = db.Column(db.TEXT) lab_director = db.Column(db.TEXT) lab_contactor = db.Column(db.TEXT) def __repr__(self): return '<Lab_Form {}'.format(self.lab_name, self.lab_school, self.lab_introduction, self.lab_location, self.lab_postcode, self.lab_supportunit, self.lab_director, self.lab_contactor) def get_info(self, name): """ 根据名称查询数据库 :param name: 实验室名称 :return: 实验室基本信息 """ info = Lab_Form.query.filter_by(lab_name=name).first() return info def select_info(self): """ 获取第page页数据 :param page: 页数 :return: 分页后的数据 """ try: info = Lab_Form.query return info except IOError: return None def search_box(self, name): """ 根据搜索框对实验室模糊搜索 :param name: 搜索框中输入的不完全实验室名称 :return: 通过模糊搜索之后得到结果的陈列 """ info = Lab_Form.query.filter( or_(Lab_Form.lab_name.like('%' + name + '%'))) return info
class Basic_info(db.Model): __tablename__ = 'basic_info' id = db.Column(db.INTEGER, primary_key=True) avator = db.Column(db.TEXT) name = db.Column(db.TEXT) college = db.Column(db.TEXT) institute = db.Column(db.TEXT) tel = db.Column(db.TEXT) email = db.Column(db.TEXT) C = db.Column(db.INT) J = db.Column(db.INT) Q = db.Column(db.INT) def __repr__(self): return 'info:{},{}'.format(self.id, self.name) @staticmethod def get_basic_info(id, path): info = Basic_info.query.filter_by(id=id).first() college = info.college name = info.name avator = Avator.get_avator(id, path) institute = info.institute tel = info.tel email = info.email c = info.C j = info.J q = info.Q C = '长江学者' if c else '' J = '杰出青年' if j else '' Q = '千人计划' if q else '' return name, college, avator, institute, tel, email, C, J, Q def search_box(self, name): """ 根据搜索框对专家的模糊搜索 :param name: 搜索框中输入的不完全专家名称 :return: 通过模糊搜索之后得到结果的陈列 """ info = Basic_info.query.filter( or_(Basic_info.name.like('%' + name + '%'))) return info # 返回对应id专家的详细信息 # def get_basic_info(id): # info = basic_info.query.filter_by(id=id).first() # # college = info.college # name = info.name # institute = info.institute # tel = info.tel # email = info.email # c = info.C # j = info.J # q = info.Q # C = '长江学者' if c else '' # J = '杰出青年' if j else '' # Q = '千人计划' if q else '' # # return college, name, institute, tel, email, C, J, Q @staticmethod # 返回id编号从a到b专家的查询结果,可以直接调用pignate def get_many(a, b): """ 获得编号从a到b的专家的基本信息 :param a: :param b: :return: """ # 查询专家基本信息的表 info = Basic_info.query.filter(Basic_info.id >= a, Basic_info.id <= b) return info
class UserMixin(BaseModelMixin): email = db.Column(CIText, nullable=False, unique=True) phone = db.Column(db.Text, nullable=True, unique=True) hashed_pw = db.Column(db.Text, nullable=False) is_admin = db.Column(db.Boolean, nullable=False, default=False) is_active = db.Column(db.Boolean, default=True, nullable=False) @declared_attr def clients(self): from .client import Client return relationship("Client", backref="user") @declared_attr def activator_tokens(self): from .activator_token import ActivatorToken return relationship("ActivatorToken", backref="user") def has_ever_logged_in(self): return len(self.clients) > 0 def after_login_redirect_desintation(self): try: return self.after_login_desintation() except AttributeError: return '/dashboard' def set_password(self, plaintext_password): self.hashed_pw = bcrypt.hashpw(plaintext_password.encode('utf-8'), bcrypt.gensalt())\ .decode('utf-8') def hashed_pw_matches_plaintext(self, plaintext_password): try_hash = bcrypt.hashpw(plaintext_password.encode('utf-8'), self.hashed_pw.encode('utf-8')) return try_hash.decode('utf-8') == self.hashed_pw def send_email(self, to, subject, content): sg = sendgrid.SendGridAPIClient(apikey=current_app.config['SENDGRID_API_KEY']) from_email = Email(current_app.config['SENDGRID_DEFAULT_FROM']) to_email = Email(to) subject = subject content = Content("text/html", content) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) return response.status_code def send_default_activator_email(self, subject, text_main, text_second='Please click the button below to confirm your email.', title='Activate your account', template='default_alert_email.html', function='default'): # Create the activator token. from fuser.activator_token import ActivatorToken activator_token = ActivatorToken.activator_token_for_user(self, function) status_code = self.send_email(to=self.email, subject=subject, content=render_template(template, title=title, text_main=text_main, text_second=text_second, button_href= "http://" + current_app.config['SERVER_NAME'] + '/auth/set_password/' + activator_token.activator_code, button_text='Activate account & Set Password', ))