19Flask的model和orm

Flask的model

import datetime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
from sqlalchemy.orm import relationship
Base = declarative_base()


class Users(Base):
    __tablename__ = 'users'  # 數據庫表名稱
    id = Column(Integer, primary_key=True)  # id 主鍵
    name = Column(String(32), index=True, nullable=False)  # name列,索引,不可爲空
    #email = Column(String(32), unique=True)
    age = Column(Integer,default=0)
    #datetime.datetime.now不能加括號,加了括號,之後永遠是當前時間
    #ctime = Column(DateTime, default=datetime.datetime.now)
    #extra = Column(Text, nullable=True)

    # __table_args__ = (
    #     UniqueConstraint('id', 'name', name='uix_id_name'), #聯合惟一
    #     Index('ix_id_name', 'name', 'email'), #索引
    # )
    def __repr__(self):
        return self.name


class Hobby(Base):
    __tablename__ = 'hobby'
    id = Column(Integer, primary_key=True)
    caption = Column(String(50), default='籃球')


class Person(Base):
    __tablename__ = 'person'
    nid = Column(Integer, primary_key=True)
    name = Column(String(32), index=True, nullable=True)
    # hobby指的是tablename而不是類名,
    hobby_id = Column(Integer, ForeignKey("hobby.id"))
    # 跟數據庫無關,不會新增字段,只用於快速鏈表操做
    # 類名,backref用於反向查詢,uselist=False
    hobby = relationship('Hobby', backref='pers')
    def __repr__(self):
        return self.name


class Boy2Girl(Base):
    __tablename__ = 'boy2girl'
    id = Column(Integer, primary_key=True, autoincrement=True)
    girl_id = Column(Integer, ForeignKey('girl.id'))
    boy_id = Column(Integer, ForeignKey('boy.id'))


class Girl(Base):
    __tablename__ = 'girl'
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)



class Boy(Base):
    __tablename__ = 'boy'

    id = Column(Integer, primary_key=True, autoincrement=True)
    hostname = Column(String(64), unique=True, nullable=False)

    # 與生成表結構無關,僅用於查詢方便,放在哪一個單表中均可以
    girl = relationship('Girl', secondary='boy2girl', backref='boys')


def init_db():
    """
    根據類建立數據庫表
    :return:
    """
    engine = create_engine(
        "mysql+pymysql://root:123@127.0.0.1:3306/flask?charset=utf8",
        max_overflow=0,  # 超過鏈接池大小外最多建立的鏈接
        pool_size=5,  # 鏈接池大小
        pool_timeout=30,  # 池中沒有線程最多等待的時間,不然報錯
        pool_recycle=-1  # 多久以後對線程池中的線程進行一次鏈接的回收(重置)
    )

    Base.metadata.create_all(engine)

def drop_db():
    """
    根據類刪除數據庫表
    :return:
    """
    engine = create_engine(
        "mysql+pymysql://root:123@127.0.0.1:3306/flask?charset=utf8",
        max_overflow=0,  # 超過鏈接池大小外最多建立的鏈接
        pool_size=5,  # 鏈接池大小
        pool_timeout=30,  # 池中沒有線程最多等待的時間,不然報錯
        pool_recycle=-1  # 多久以後對線程池中的線程進行一次鏈接的回收(重置)
    )

    Base.metadata.drop_all(engine)

if __name__ == '__main__':
    #drop_db()
    init_db()

Flask的orm操做

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Users
#"mysql+pymysql://root@127.0.0.1:3306/aaa"
engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/flask", max_overflow=0, pool_size=5)
Connection = sessionmaker(bind=engine)

# 每次執行數據庫操做時,都須要建立一個Connection
con = Connection()

# ############# 執行ORM操做 #############
obj1 = Users(name="lqz",age=123)
con.add(obj1)
# 提交事務
con.commit()

# 關閉session,實際上是將鏈接放回鏈接池
con.close()

Flask的線程安全的ORM操做

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session
from models import Users

engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/flask", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)

"""
# 線程安全,基於本地線程實現每一個線程用同一個session
# 特殊的:scoped_session中有原來方法的Session中的一下方法:

public_methods = (
    '__contains__', '__iter__', 'add', 'add_all', 'begin', 'begin_nested',
    'close', 'commit', 'connection', 'delete', 'execute', 'expire',
    'expire_all', 'expunge', 'expunge_all', 'flush', 'get_bind',
    'is_modified', 'bulk_save_objects', 'bulk_insert_mappings',
    'bulk_update_mappings',
    'merge', 'query', 'refresh', 'rollback',
    'scalar'
)
"""
#scoped_session類並無繼承Session,可是卻又它的全部方法
session = scoped_session(Session)
# ############# 執行ORM操做 #############
obj1 = Users(name="jason")
session.add(obj1)

# 提交事務
session.commit()
# 關閉session
session.close()
相關文章
相關標籤/搜索