88、flask之SQLAlchemy

本篇导航:

  • 介绍
  • 使用
  • SQLAlchemy-Utils

一. 介绍

SQLAlchemy是一个基于Python实现的ORM框架。该框架建立在 DB API之上,使用关系对象映射进行数据库操作,简言之便是:将类和对象转换成SQL,然后使用数据API执行SQL并获取执行结果。

pip install sqlalchemy -i http://pypi.douban.com/simple  --trusted-host pypi.douban.com 

组成部分:

  • Engine,框架的引擎
  • Connection Pooling ,数据库连接池
  • Dialect,选择连接数据库的DB API种类
  • Schema/Types,架构和类型
  • SQL Exprression Language,SQL表达式语言

SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:

MySQL-Python
    mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>

pymysql
    mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]

MySQL-Connector
    mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>

cx_Oracle
    oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]

更多:http://docs.sqlalchemy.org/en/latest/dialects/index.html



二. 使用

1、 执行原生SQL语句

import time
import threading
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.engine.base import Engine

engine = create_engine(
    "mysql+pymysql://root:[email protected]:3306/t1?charset=utf8",
    max_overflow=0,  # 超过连接池大小外最多创建的连接
    pool_size=5,  # 连接池大小
    pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
    pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
)

def task(arg):
    conn = engine.raw_connection()
    cursor = conn.cursor()
    cursor.execute(
        "select * from t1"
    )
    result = cursor.fetchall()
    cursor.close()
    conn.close()

for i in range(20):
    t = threading.Thread(target=task, args=(i,))
    t.start()

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import threading
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.engine.base import Engine

engine = create_engine("mysql+pymysql://root:[email protected]:3306/t1", max_overflow=0, pool_size=5)

def task(arg):
    conn = engine.contextual_connect()
    with conn:
        cur = conn.execute(
            "select * from t1"
        )
        result = cur.fetchall()
        print(result)

for i in range(20):
    t = threading.Thread(target=task, args=(i,))
    t.start()

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import threading
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.engine.base import Engine
from sqlalchemy.engine.result import ResultProxy
engine = create_engine("mysql+pymysql://root:[email protected]:3306/t1", max_overflow=0, pool_size=5)

def task(arg):
    cur = engine.execute("select * from t1")
    result = cur.fetchall()
    cur.close()
    print(result)

for i in range(20):
    t = threading.Thread(target=task, args=(i,))
    t.start()

注意: 查看连接 show status like ‘Threads%‘;

2.、ORM

a.、创建数据库表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
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

Base = declarative_base()

class Users(Base):
    __tablename__ = ‘users‘

    id = Column(Integer, primary_key=True)
    name = Column(String(32), index=True, nullable=False)
    # email = Column(String(32), unique=True)
    # 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 init_db():
    """
    根据类创建数据库表
    :return:
    """
    engine = create_engine(
        "mysql+pymysql://root:[email protected]:3306/s6?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:[email protected]:3306/s6?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()

创建单表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
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)
    name = Column(String(32), index=True)
    age = Column(Integer, default=18)
    email = Column(String(32), unique=True)
    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‘, ‘extra‘),
    )

class Hosts(Base):
    __tablename__ = ‘hosts‘

    id = Column(Integer, primary_key=True)
    name = Column(String(32), index=True)
    ctime = Column(DateTime, default=datetime.datetime.now)

# ##################### 一对多示例 #########################
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_id = Column(Integer, ForeignKey("hobby.id"))

    # 与生成表结构无关,仅用于查询方便
    hobby = relationship("Hobby", backref=‘pers‘)

# ##################### 多对多示例 #########################

class Server2Group(Base):
    __tablename__ = ‘server2group‘
    id = Column(Integer, primary_key=True, autoincrement=True)
    server_id = Column(Integer, ForeignKey(‘server.id‘))
    group_id = Column(Integer, ForeignKey(‘group.id‘))

class Group(Base):
    __tablename__ = ‘group‘
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)

    # 与生成表结构无关,仅用于查询方便
    servers = relationship(‘Server‘, secondary=‘server2group‘, backref=‘groups‘)

class Server(Base):
    __tablename__ = ‘server‘

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

def init_db():
    """
    根据类创建数据库表
    :return:
    """
    engine = create_engine(
        "mysql+pymysql://root:[email protected]:3306/s6?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:[email protected]:3306/s6?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()

创建多个表并包含Fk、M2M关系

b.、操作数据库表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Users

engine = create_engine("mysql+pymysql://root:[email protected]:3306/s6", max_overflow=0, pool_size=5)
##############方式一########################
Session = sessionmaker(bind=engine)

# 每次执行数据库操作时,都需要创建一个session
session = Session()

# ############# 执行ORM操作 #############
obj1 = Users(name="alex1")
session.add(obj1)

# 提交事务
session.commit()
# 关闭session
session.close()

######################方式二####################
# 方式二:支持线程安全,为每个线程创建一个session
# - threading.Local
# - 唯一标识
# ScopedSession对象
# self.registry(), 加括号 创建session
# self.registry(), 加括号 创建session
# self.registry(), 加括号 创建session
from greenlet import getcurrent as get_ident

Session = sessionmaker(bind=engine)

session = scoped_session(Session,get_ident)
# session.add
# 操作
session.remove()

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import threading

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
from db import Users

engine = create_engine("mysql+pymysql://root:[email protected]:3306/s6", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)

def task(arg):
    session = Session()

    obj1 = Users(name="alex1")
    session.add(obj1)

    session.commit()

for i in range(10):
    t = threading.Thread(target=task, args=(i,))
    t.start()

多线程执行示例

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import threading

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
from sqlalchemy.sql import text

from db import Users, Hosts

engine = create_engine("mysql+pymysql://root:[email protected]:3306/s6", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)

session = Session()

# ################ 添加 ################
"""
obj1 = Users(name="wupeiqi")
session.add(obj1)

session.add_all([
    Users(name="wupeiqi"),
    Users(name="alex"),
    Hosts(name="c1.com"),
])
session.commit()
"""

# ################ 删除 ################
"""
session.query(Users).filter(Users.id > 2).delete()
session.commit()
"""
# ################ 修改 ################
"""
session.query(Users).filter(Users.id > 0).update({"name" : "099"})
session.query(Users).filter(Users.id > 0).update({Users.name: Users.name + "099"}, synchronize_session=False)
session.query(Users).filter(Users.id > 0).update({"age": Users.age + 1}, synchronize_session="evaluate")
session.commit()
"""
# ################ 查询 ################
"""
r1 = session.query(Users).all()
r2 = session.query(Users.name.label(‘xx‘), Users.age).all()
r3 = session.query(Users).filter(Users.name == "alex").all()
r4 = session.query(Users).filter_by(name=‘alex‘).all()
r5 = session.query(Users).filter_by(name=‘alex‘).first()
r6 = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name=‘fred‘).order_by(Users.id).all()
r7 = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name=‘ed‘).all()
"""

session.close()

基本增删改查示例

# 条件
ret = session.query(Users).filter_by(name=‘alex‘).all()
ret = session.query(Users).filter(Users.id > 1, Users.name == ‘eric‘).all()
ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == ‘eric‘).all()
ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()
ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()
ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name=‘eric‘))).all()
from sqlalchemy import and_, or_
ret = session.query(Users).filter(and_(Users.id > 3, Users.name == ‘eric‘)).all()
ret = session.query(Users).filter(or_(Users.id < 2, Users.name == ‘eric‘)).all()
ret = session.query(Users).filter(
    or_(
        Users.id < 2,
        and_(Users.name == ‘eric‘, Users.id > 3),
        Users.extra != ""
    )).all()

# 通配符
ret = session.query(Users).filter(Users.name.like(‘e%‘)).all()
ret = session.query(Users).filter(~Users.name.like(‘e%‘)).all()

# 限制
ret = session.query(Users)[1:2]

# 排序
ret = session.query(Users).order_by(Users.name.desc()).all()
ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all()

# 分组
from sqlalchemy.sql import func

ret = session.query(Users).group_by(Users.extra).all()
ret = session.query(
    func.max(Users.id),
    func.sum(Users.id),
    func.min(Users.id)).group_by(Users.name).all()

ret = session.query(
    func.max(Users.id),
    func.sum(Users.id),
    func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all()

# 连表

ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all()

ret = session.query(Person).join(Favor).all()

ret = session.query(Person).join(Favor, isouter=True).all()

# 组合
q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union(q2).all()

q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union_all(q2).all()

常用操作

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import threading

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from sqlalchemy.engine.result import ResultProxy
from db import Users, Hosts

engine = create_engine("mysql+pymysql://root:[email protected]:3306/s6", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)

session = Session()

# 查询
# cursor = session.execute(‘select * from users‘)
# result = cursor.fetchall()

# 添加
cursor = session.execute(‘insert into users(name) values(:value)‘,params={"value":‘wupeiqi‘})
session.commit()
print(cursor.lastrowid)

session.close()

原生SQL语句

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import threading

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from sqlalchemy.engine.result import ResultProxy
from db import Users, Hosts, Hobby, Person

engine = create_engine("mysql+pymysql://root:[email protected]:3306/s6?charset=utf8", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
session = Session()
# 添加
"""
session.add_all([
    Hobby(caption=‘乒乓球‘),
    Hobby(caption=‘羽毛球‘),
    Person(name=‘张三‘, hobby_id=3),
    Person(name=‘李四‘, hobby_id=4),
])

person = Person(name=‘张九‘, hobby=Hobby(caption=‘姑娘‘))
session.add(person)

hb = Hobby(caption=‘人妖‘)
hb.pers = [Person(name=‘文飞‘), Person(name=‘博雅‘)]
session.add(hb)

session.commit()
"""

# 使用relationship正向查询
"""
v = session.query(Person).first()
print(v.name)
print(v.hobby.caption)
"""

# 使用relationship反向查询
"""
v = session.query(Hobby).first()
print(v.caption)
print(v.pers)
"""

session.close()

基于relationship操作ForeignKey

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import threading

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from sqlalchemy.engine.result import ResultProxy
from db import Users, Hosts, Hobby, Person, Group, Server, Server2Group

engine = create_engine("mysql+pymysql://root:[email protected]:3306/s6?charset=utf8", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
session = Session()
# 添加
"""
session.add_all([
    Server(hostname=‘c1.com‘),
    Server(hostname=‘c2.com‘),
    Group(name=‘A组‘),
    Group(name=‘B组‘),
])
session.commit()

s2g = Server2Group(server_id=1, group_id=1)
session.add(s2g)
session.commit()

gp = Group(name=‘C组‘)
gp.servers = [Server(hostname=‘c3.com‘),Server(hostname=‘c4.com‘)]
session.add(gp)
session.commit()

ser = Server(hostname=‘c6.com‘)
ser.groups = [Group(name=‘F组‘),Group(name=‘G组‘)]
session.add(ser)
session.commit()
"""

# 使用relationship正向查询
"""
v = session.query(Group).first()
print(v.name)
print(v.servers)
"""

# 使用relationship反向查询
"""
v = session.query(Server).first()
print(v.hostname)
print(v.groups)
"""

session.close()

基于relationship操作m2m

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import threading

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
from sqlalchemy.sql import text, func
from sqlalchemy.engine.result import ResultProxy
from db import Users, Hosts, Hobby, Person, Group, Server, Server2Group

engine = create_engine("mysql+pymysql://root:[email protected]:3306/s6?charset=utf8", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
session = Session()

# 关联子查询
subqry = session.query(func.count(Server.id).label("sid")).filter(Server.id == Group.id).correlate(Group).as_scalar()
result = session.query(Group.name, subqry)
"""
SELECT `group`.name AS group_name, (SELECT count(server.id) AS sid
FROM server
WHERE server.id = `group`.id) AS anon_1
FROM `group`
"""

# 原生SQL
"""
# 查询
cursor = session.execute(‘select * from users‘)
result = cursor.fetchall()

# 添加
cursor = session.execute(‘insert into users(name) values(:value)‘,params={"value":‘wupeiqi‘})
session.commit()
print(cursor.lastrowid)
"""

session.close()

其他

基本增删改查补充

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import threading

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
from sqlalchemy.sql import text

from db import Users, Hosts

engine = create_engine("mysql+pymysql://root:[email protected]:3306/s6", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)

session = Session()

# ################ 添加 ################
"""
obj1 = Users(name="wupeiqi")
session.add(obj1)

#批量添加
session.add_all([
    Users(name="wupeiqi"),
    Users(name="alex"),
    Hosts(name="c1.com"),
])
session.commit()
"""

# ################ 删除 ################
"""
session.query(Users).filter(Users.id > 2).delete()
session.commit()
"""
# ################ 修改 ################
"""
session.query(Users).filter(Users.id > 0).update({"name" : "099"})
session.query(Users).filter(Users.id > 0).update({Users.name: Users.name + "099"}, synchronize_session=False) #字符串
session.query(Users).filter(Users.id > 0).update({"age": Users.age + 1}, synchronize_session="evaluate")  #数字
session.commit()
"""
# ################ 查询 ################
"""
r1 = session.query(Users).all()
r2 = session.query(Users.name.label(‘xx‘), Users.age).all()   #lable #as xx
r3 = session.query(Users).filter(Users.name == "alex").all()
r4 = session.query(Users).filter_by(name=‘alex‘).all()   #如果里面写条件就用filter_by,和上面filter查询是一回事,只是一种不同的方式
r5 = session.query(Users).filter_by(name=‘alex‘).first()
r6 = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name=‘fred‘).order_by(Users.id).all()  #查询里面如果有动态传参的时候,吧它包在text里面,:value,:name这样的语法后面用.params来进行格式化
r7 = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name=‘ed‘).all()  #上面的这个方式也可以用这一种 ,直接可以进行SQL语句的查询
"""

session.close()



三、SQLAlchemy-Utils

1、由于sqlalchemy中没有提供choice方法,所以借助SQLAlchemy-Utils组件提供的choice方法

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
from sqlalchemy_utils import ChoiceType

Base = declarative_base()
class Xuan(Base):
    __tablename__ = ‘xuan‘
    types_choices = (
        (1,‘欧美‘),
        (2,‘日韩‘),
        (3,‘老男孩‘),
    )
    id = Column(Integer,primary_key=True,autoincrement=True)
    name = Column(String(64))
    types = Column(ChoiceType(types_choices,Integer()))

    __table_args__ = {
        ‘mysql_engine‘:‘Innodb‘,
        ‘mysql_charset‘:‘utf8‘,
    }

engine = create_engine(
    "mysql+pymysql://root:[email protected]:3306/ttt2?charset=utf8",
    max_overflow=0,  # 超过连接池大小外最多创建的连接
    pool_size=5,  # 连接池大小
    pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
    pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
)

Base.metadata.create_all(engine)

查询:
  result_list = session.query(Xuan).all()
  for item in result_list:
    print(item.types.code,item.types.value)

2、scoped_session

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session
engine = create_engine(
        "mysql+pymysql://root:[email protected]:3306/ttt?charset=utf8",
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,  # 连接池大小
        pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
)
SessionFactory = sessionmaker(bind=engine)
# 方式一:由于无法提供线程共享功能,所有在开发时要注意,在每个线程中自己创建 session。
#         from sqlalchemy.orm.session import Session
#         自己具有操作数据库的:‘close‘, ‘commit‘, ‘connection‘, ‘delete‘, ‘execute‘, ‘expire‘,.....
session = SessionFactory()

# print(‘原生session‘,session)
# 操作
session.close()

# 方式二:支持线程安全,为每个线程创建一个session
#               - threading.Local
#               - 唯一标识
# ScopedSession对象
#       self.registry(), 加括号 创建session
#       self.registry(), 加括号 创建session
#       self.registry(), 加括号 创建session
from greenlet import getcurrent as get_ident
session = scoped_session(SessionFactory,get_ident)
# session.add
# 操作
session.remove()

3、Flask-SQLAlchemy和Flask-Migrate 组件

4、Flask-SQLAlchemy:吧Flask和SQLAlchemy结合在一起,粘合剂
    在__init__.py 文件中
        1 引入Flask-SQLAlchemy    中的SQLAlchemy,实例化了一个SQLAlchemy对象
        2 注册Flask-SQLAlchemy:
            - 有两种方式
                方式一: 在函数里面,SQLAlchemy(app)  #如果想在其他地方使用这种方式就不好使了
                方式二: 在全局:
                    db = SQLAlchemy(),
                    在函数里面 db.init_app(app)  #调用init_app方法吧app放进去了
        3、导入models的类
        4、导入的类中继承了db.model,其实本质上还是继承了Base类
        5、manage.py 创建数据库表,可以通过命令来创建。借助Flask-Migrate组件来完成
5、Flask-Migrate:
    -旧5 被毙掉了:在manage.py里面导入db,以后执行db.create_all()创建表,以后执行drop_all()删除表
      这样不好,我们可以和Flask-Migrate结合起来用
    -新5:Flask-Migrate
        - 安装组件:pip install Flask-Migrate
        - 5.1 导入
            from flask_migrate import Migrate, MigrateCommand
            from app import db, app
        - 5.2 migrate = Migrate(app,db) #创建实例
        - 5.3 创建命令
            manager.add_command("db",MigrateCommand)
        - 5.4 执行命令
            python manage.py db init  #只执行第一次
            python manage.py db migrate
            python manage.py db upgrade
    在执行命令之前,得先连接数据库,他才会知道吧表放在那里,

4、详说注册SQLAlchemy的两种方式

1)方式一

from flask_sqlalchemy import SQLAlchemy
from flask import FLask
app = Flask(__name__)
app.config[‘SQLALCHEMY_DATABASE_URI‘] =     "mysql://root:[email protected]/test"
db = SQLAlchemy(app)

2)方式二:

from flask_sqlalchemy import SQLAlchemy
from flask import FLask
db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    return app

5、操作数据库

通过上面注册了SQLAlchemy,就直接可以从db.session了

#方式一
        db.session  #会自动创建一个session
        db.session.add()
        db.session.query(models.User.id,models.User.name).all()
        db.session.commit()
        db.session.remove()
#方式二
        导入models
        models.User.query

6、flask中所有用到过的组件

所有用过的组件
    Flask
    连接数据库的两种操作
        要么DBUtils:用于执行原生SQL的
            用自己的util里面的sqlhelper来完成
        要么SQLAlchemy:遵循他自己的语法来链接
            方式一:SQLAlchemy(app)这种方式有局限性,如果我在其他地方也得用到呢?可以吧它写到全局
            方式二:优点,
                实例化一下:db = SQLAlchemy()
                注册:
                    在settings里面配置一下数据库链接方式
                        SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:[email protected]:3306/s6?charset=utf8"
                        SQLALCHEMY_POOL_SIZE = 2
                        SQLALCHEMY_POOL_TIMEOUT = 30
                        SQLALCHEMY_POOL_RECYCLE = -1
                    Flask-SQLAlchemy: db.init_app(app)

    Flask-Session  #用于吧session保存在其他地方
    Flask-Script  #生成命令
    Flask-Migrate   #数据库迁移
    Flask-SQLAlchemy  #将Flask和SQLAlchemy很好的结合在一起
        #本质、:每次操作数据库就会自动创建一个session连接,完了自动关闭
    Blinker  #信号
    Wtforms  #FORM组件
    用到的组件和版本
        pip3 freeze  #获取环境中所有安装的模块
        pip3 freeze > a.txt
        pip3 freeze > requirements.txt
        #pip3 install pipreqs  #帮你找到当前程序的所有模块,并且自动生成 requirements.txt文件,写入内容
        pipreqs ./  #根目录

        以后别人给你一个程序,告知你一个文件夹需要安装的组件:requirements.txt
             进入程序目录:
                pip install -r requirements.txt #就会把设计到的所有的组件就会装上 

        结构:
            app
                static
                templates
                views
                __init__.py
                models.py

原文地址:https://www.cnblogs.com/liluning/p/8312622.html

时间: 2024-10-29 20:39:21

88、flask之SQLAlchemy的相关文章

flask 使用 SQLAlchemy 的两种方式

1. 使用 flask-SQLAlchemy 扩展 # flask-ext-sqlalchemy.py from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db =

flask之SQLAlchemy

SQLAlchemy 1.介绍 SQLAlchemy是一个基于Python实现的ORM框架.该框架建立在 DB API之上,使用关系对象映射进行数据库操作,简言之便是:将类和对象转换成SQL,然后使用数据API执行SQL并获取执行结果. pip3 install sqlalchemy 组成部分: Engine,框架的引擎 Connection Pooling ,数据库连接池 Dialect,选择连接数据库的DB API种类 Schema/Types,架构和类型 SQL Exprression L

python web开发-flask中sqlalchemy的使用

SqlAlchemy是一个python的ORM框架. 在flask中有一个flask-sqlalchemy的扩展,使用起来很方便. 1.       创建一个sqlalchemy的Model模块 创建一个models.py的模块 创建model的时候,首先引入flask-sqlalchemy的扩展 from flask import Flask from flask_sqlalchemy import SQLAlchemy 然后初始化app和sqlalchemy app = Flask(__na

flask mysql sqlalchemy教程

1.建立models_base文件 连接数据库 import logging import ast import simplejson as json import time from flask_sqlalchemy import SQLAlchemy from flask import Flask from commons.entity import rds_mongo app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] =

【Flask】Sqlalchemy 外键

### 外键:使用SQLAlchemy创建外键非常简单.在从表中增加一个字段,指定这个字段外键的是哪个表的哪个字段就可以了.从表中外键的字段,必须和父表的主键字段类型保持一致.示例代码如下: 1 from sqlalchemy import create_engine, Column, Integer, String, Text, ForeignKey 2 3 from sqlalchemy.ext.declarative import declarative_base 4 from sqlal

【Flask】Sqlalchemy group_by having

### group_by:根据某个字段进行分组.比如想要根据性别进行分组,来统计每个分组分别有多少人 ### having: having是对查找结果进一步过滤.比如只想要看未成年人的数量,那么可以首先对年龄进行分组统计人数,然后再对分组进行having过滤.示例代码如下: 1 # coding:utf-8 2 # Author: liangjun.chen 3 4 from datetime import datetime 5 from sqlalchemy import create_eng

【Flask】Sqlalchemy join

### join:1. join分为left join(左外连接)和right join(右外连接)以及内连接(等值连接).2. 参考的网页:http://www.jb51.net/article/15386.htm3. 在sqlalchemy中,使用join来完成内连接.在写join的时候,如果不写join的条件,那么默认将使用外键来作为条件连接.4. query查找出来什么值,不会取决于join后面的东西,而是取决于query方法中传了什么参数.就跟原生sql中的select 后面那一个一样

Flask使用SQLAlchemy连接mysql

models.py from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column from sqlalchemy import Integer,String,Text,Date,DateTime from sqlalchemy import create_engine Base = declarative_base() class Users(Base): __tablename__ =

Flask的sqlalchemy SQL练习

models.py from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Enum, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship # 数据库配置信息 HOST = "127.0.0.1"