Flask - SQLAlchemy

Posted 你与断剑皆遗憾

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask - SQLAlchemy相关的知识,希望对你有一定的参考价值。

一、SQLAlchemy介绍

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

1.安装

pip3 install sqlalchemy

 

2.组成部分

  • 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:123@127.0.0.1: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()

 

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 import threading
 5 import sqlalchemy
 6 from sqlalchemy import create_engine
 7 from sqlalchemy.engine.base import Engine
 8 
 9 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=0, pool_size=5)
10 
11 
12 def task(arg):
13     conn = engine.contextual_connect()
14     with conn:
15         cur = conn.execute(
16             "select * from t1"
17         )
18         result = cur.fetchall()
19         print(result)
20 
21 
22 for i in range(20):
23     t = threading.Thread(target=task, args=(i,))
24     t.start()
View Code
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 import threading
 5 import sqlalchemy
 6 from sqlalchemy import create_engine
 7 from sqlalchemy.engine.base import Engine
 8 from sqlalchemy.engine.result import ResultProxy
 9 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=0, pool_size=5)
10 
11 
12 def task(arg):
13     cur = engine.execute("select * from t1")
14     result = cur.fetchall()
15     cur.close()
16     print(result)
17 
18 
19 for i in range(20):
20     t = threading.Thread(target=task, args=(i,))
21     t.start()
View Code

 

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

 

2. ORM

a. 创建数据库表

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import datetime
 4 from sqlalchemy import create_engine
 5 from sqlalchemy.ext.declarative import declarative_base
 6 from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
 7 
 8 Base = declarative_base()
 9 
10 
11 class Users(Base):
12     __tablename__ = \'users\'
13 
14     id = Column(Integer, primary_key=True)
15     name = Column(String(32), index=True, nullable=False)
16     # email = Column(String(32), unique=True)
17     # ctime = Column(DateTime, default=datetime.datetime.now)
18     # extra = Column(Text, nullable=True)
19 
20     __table_args__ = (
21         # UniqueConstraint(\'id\', \'name\', name=\'uix_id_name\'),
22         # Index(\'ix_id_name\', \'name\', \'email\'),
23     )
24 
25 
26 def init_db():
27     """
28     根据类创建数据库表
29     :return: 
30     """
31     engine = create_engine(
32         "mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8",
33         max_overflow=0,  # 超过连接池大小外最多创建的连接
34         pool_size=5,  # 连接池大小
35         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
36         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
37     )
38 
39     Base.metadata.create_all(engine)
40 
41 
42 def drop_db():
43     """
44     根据类删除数据库表
45     :return: 
46     """
47     engine = create_engine(
48         "mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8",
49         max_overflow=0,  # 超过连接池大小外最多创建的连接
50         pool_size=5,  # 连接池大小
51         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
52         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
53     )
54 
55     Base.metadata.drop_all(engine)
56 
57 
58 if __name__ == \'__main__\':
59     drop_db()
60     init_db()
61 
62 创建单表
创建单表

 

  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 import datetime
  4 from sqlalchemy import create_engine
  5 from sqlalchemy.ext.declarative import declarative_base
  6 from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
  7 from sqlalchemy.orm import relationship
  8 
  9 Base = declarative_base()
 10 
 11 
 12 # ##################### 单表示例 #########################
 13 class Users(Base):
 14     __tablename__ = \'users\'
 15 
 16     id = Column(Integer, primary_key=True)
 17     name = Column(String(32), index=True)
 18     age = Column(Integer, default=18)
 19     email = Column(String(32), unique=True)
 20     ctime = Column(DateTime, default=datetime.datetime.now)
 21     extra = Column(Text, nullable=True)
 22 
 23     __table_args__ = (
 24         # UniqueConstraint(\'id\', \'name\', name=\'uix_id_name\'),
 25         # Index(\'ix_id_name\', \'name\', \'extra\'),
 26     )
 27 
 28 
 29 class Hosts(Base):
 30     __tablename__ = \'hosts\'
 31 
 32     id = Column(Integer, primary_key=True)
 33     name = Column(String(32), index=True)
 34     ctime = Column(DateTime, default=datetime.datetime.now)
 35 
 36 
 37 # ##################### 一对多示例 #########################
 38 class Hobby(Base):
 39     __tablename__ = \'hobby\'
 40     id = Column(Integer, primary_key=True)
 41     caption = Column(String(50), default=\'篮球\')
 42 
 43 
 44 class Person(Base):
 45     __tablename__ = \'person\'
 46     nid = Column(Integer, primary_key=True)
 47     name = Column(String(32), index=True, nullable=True)
 48     hobby_id = Column(Integer, ForeignKey("hobby.id"))
 49 
 50     # 与生成表结构无关,仅用于查询方便
 51     hobby = relationship("Hobby", backref=\'pers\')
 52 
 53 
 54 # ##################### 多对多示例 #########################
 55 
 56 class Server2Group(Base):
 57     __tablename__ = \'server2group\'
 58     id = Column(Integer, primary_key=True, autoincrement=True)
 59     server_id = Column(Integer, ForeignKey(\'server.id\'))
 60     group_id = Column(Integer, ForeignKey(\'group.id\'))
 61 
 62 
 63 class Group(Base):
 64     __tablename__ = \'group\'
 65     id = Column(Integer, primary_key=True)
 66     name = Column(String(64), unique=True, nullable=False)
 67 
 68     # 与生成表结构无关,仅用于查询方便
 69     servers = relationship(\'Server\', secondary=\'server2group\', backref=\'groups\')
 70 
 71 
 72 class Server(Base):
 73     __tablename__ = \'server\'
 74 
 75     id = Column(Integer, primary_key=True, autoincrement=True)
 76     hostname = Column(String(64), unique=True, nullable=False)
 77 
 78 
 79 def init_db():
 80     """
 81     根据类创建数据库表
 82     :return: 
 83     """
 84     engine = create_engine(
 85         "mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8",
 86         max_overflow=0,  # 超过连接池大小外最多创建的连接
 87         pool_size=5,  # 连接池大小
 88         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
 89         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
 90     )
 91 
 92     Base.metadata.create_all(engine)
 93 
 94 
 95 def drop_db():
 96     """
 97     根据类删除数据库表
 98     :return: 
 99     """
100     engine = create_engine(
101         "mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8",
102         max_overflow=0,  # 超过连接池大小外最多创建的连接
103         pool_size=5,  # 连接池大小
104         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
105         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
106     )
107 
108     Base.metadata.drop_all(engine)
109 
110 
111 if __name__ == \'__main__\':
112     drop_db()
113     init_db()
114 
115 创建多个表并包含Fk、M2M关系
创建多个表并包含Fk、M2M关系

 

指定关联列:hobby = relationship("Hobby", backref=\'pers\',foreign_keys="Person.hobby_id")

 

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:123@127.0.0.1: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()

  

3.基于scoped_session实现线程安全

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from sqlalchemy.orm import sessionmaker
 4 from sqlalchemy import create_engine
 5 from sqlalchemy.orm import scoped_session
 6 from models import Users
 7 
 8 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s6", max_overflow=0, pool_size=5)
 9 Session = sessionmaker(bind=engine)
10 
11 """
12 # 线程安全,基于本地线程实现每个线程用同一个session
13 # 特殊的:scoped_session中有原来方法的Session中的一下方法:
14 
15 public_methods = (
16     \'__contains__\', \'__iter__\', \'add\', \'add_all\', \'begin\', \'begin_nested\',
17     \'close\', \'commit\', \'connection\', \'delete\', \'execute\', \'expire\',
18     \'expire_all\', \'expunge\', \'expunge_all\', \'flush\', \'get_bind\',
19     \'is_modified\', \'bulk_save_objects\', \'bulk_insert_mappings\',
20     \'bulk_update_mappings\',
21     \'merge\', \'query\', \'refresh\', \'rollback\',
22     \'scalar\'
23 )
24 """
25 session = scoped_session(Session)
26 
27 
28 # ############# 执行ORM操作 #############
29 obj1 = Users(name="alex1")
30 session.add(obj1)
31 
32 
33 
34 # 提交事务
35 session.commit()
36 # 关闭session
37 session.close()
38 
39 基于scoped_session实现线程安全
基于scoped_session实现线程安全

 

4.多线程执行示例

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 import threading
 5 
 6 from sqlalchemy.ext.declarative import declarative_base
 7 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
 8 from sqlalchemy.orm import sessionmaker, relationship
 9 from sqlalchemy import create_engine
10 from db import Users
11 
12 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s6", max_overflow=0, pool_size=5)
13 Session = sessionmaker(bind=engine)
14 
15 
16 def task(arg):
17     session = Session()
18 
19     obj1 = Users(name="alex1")
20     session.add(obj1)
21 
22     session.commit()
23 
24 
25 for i in range(10):
26     t = threading.Thread(target=task, args=(i,))
27     t.start()
28 
29 多线程执行示例
多线程执行示例

 

5.基本增删改查示例

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 import threading
 5 
 6 from sqlalchemy.ext.declarative import declarative_base
 7 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
 8 from sqlalchemy.orm import sessionmaker, relationship
 9 from sqlalchemy import create_engine
10 from sqlalchemy.sql import text
11 
12 from db import Users, Hosts
13 
14 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s6", max_overflow=0, pool_size=5)
15 Session = sessionmaker(bind=engine)
16 
17 session = Session()
18 
19 # ################ 添加 ################
20 """
21 obj1 = Users(name="wupeiqi")
22 session.add(obj1)
23 
24 session.add_all([
25     Users(name="wupeiqi"),
26     Users(name="alex"),
27     Hosts(name="c1.com"),
28 ])
29 session.commit()
30 """
31 
32 # ################ 删除 ################
33 """
34 session.query(Users).filter(Users.id > 2).delete()
35 session.commit()
36 """
37 # ################ 修改 ################
38 """
39 session.query(Users).filter(Users.id > 0).update({"name" : "099"})
40 session.query(Users).filter(Users.id > 0).update({Users.name: Users.name + "099"}, synchronize_session=False)
41 session.query(Users).filter(Users.id > 0).update({"age": Users.age + 1}, synchronize_session="evaluate")
42 session.commit()
43 """
44 # ################ 查询 ################
45 """
46 r1 = session.query(Users).all()
47 r2 = session.query(Users.name.label(\'xx\'), Users.age).all()
48 r3 = session.query(Users).filter(Users.name == "alex").all()
49 r4 = session.query(Users).filter_by(name=\'alex\').all()
50 r5 = session.query(Users).filter_by(name=\'alex\').first()
51 r6 = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name=\'fred\').order_by(Users.id).all()
52 r7 = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name=\'ed\').all()
53 """
54 
55 
56 session.close()
57 
58 基本增删改查示例
基本增删改查示例

 

6.常用操作