Flask应用的SQLAlchemy Core集成
项目描述
为Flask应用集成SQLAlchemy Core。
为在Flask(或基于Werkzeug的)应用中设置和使用SQLAlchemy Core提供了一种简单的方法。
与纯SQLAlchemy相比,使用此包的主要好处是能够在上下文局部“全局”对象中共享当前连接。
这允许在不显式传递连接对象到函数的情况下创建嵌套事务。
这反过来又使得可以在事务中运行测试函数,测试断言后将回滚事务,大大减少了测试运行时间,通过移除每次测试函数运行时持续删除和重新创建整个数据库模式的需求。
用法
设置
import os
from flask_sqlalchemy_core import FlaskSQLAlchemy
DATABASE_URL = os.environ['DATABASE_URL']
db = FlaskSQLAlchemy(DATABASE_URL)
运行查询
from sqlalchemy import select
# Create your query here
query = select(...)
with db.connect() as conn:
result = conn.execute(query)
# Do something with the result...
事务
with db.transaction() as conn:
result = conn.execute(query)
在“with”块成功退出时,事务将自动提交,如果抛出异常,则回滚。
嵌套事务
只需嵌套 with db.transaction(): 块。
这允许代码更易于重用,例如
def create_user(...):
with db.transaction() as conn:
# Create record in the users table
conn.execute(...)
# Other data for the user in some other table
conn.execute(...)
def create_client(...):
with db.transaction() as conn:
# Create record in the clients table
conn.execute(...)
# ...other data for this client...
conn.execute(...)
def setup_new_client(client_name, user_name):
with db.transaction():
create_user(user_name)
create_client(client_name)
定义表
就像您通常那样做(创建一个Metadata实例,使用它来定义您的模式)。
创建模式
metadata.create_all(db.get_engine())
测试固定值
对于与pytest一起使用,将这些放在测试目录中的 conftest.py 文件中。
注意:您可能希望在测试期间更改您的 DATABASE_URL 环境变量,以避免覆盖当前的开发数据库。
import pytest
@pytest.fixture
def db(db_schema):
with db.transaction(autocommit=False, rollback=True):
# By wrapping execution in a transaction that automatically
# gets rolled back, we can avoid having to recreate the whole
# schema for every test function run.
yield
@pytest.fixture(scope='session')
def db_schema():
engine = db.get_engine()
# Clean up, in case tables were left around from a previous run.
# This can happen if the test process was abruptly killed.
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
数据库迁移
使用 Alembic 创建数据库迁移。
数据库支持
该库目前已在 PostgreSQL(10)上进行了测试。
在其他后端(不支持检查点的后端除外,嵌套事务)上,所有功能也应正常工作。
测试
在运行测试套件之前,您需要启动一个 SQL 数据库并设置 DATABASE_URL 环境变量。
为了方便起见,您可以使用 bin/run-test-database 脚本,该脚本将自动通过 Docker 运行 PostgreSQL 实例。
脚本还将打印出适合 DATABASE_URL 的值。
完成后,只需按 Ctrl-C 停止它。
安装测试依赖项
pip install -r test_requirements.txt
运行测试套件
pytest -vvv ./tests
使用 SQLite 后端运行测试
DATABASE_URL="sqlite:///:memory:" pytest -vvv ./tests
警告:由于 SQLite 不支持嵌套事务,某些测试将被跳过。
项目详情
下载文件
下载您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。
源代码分布
构建分布
flask_sqlalchemy_core-0.1.1.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | ee3984392f80f91278bd0adb1386f747ddd03e1de3e8741f3277cf21af1ca52c |
|
MD5 | 6da8600b35c3f2c6ee49d8d1703a70a8 |
|
BLAKE2b-256 | 911a0aa7854ff459d118abd6f28eeadd15394f727118849849b219f87218ae6d |
flask_sqlalchemy_core-0.1.1-py3-none-any.whl 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | b26f7f887b0edb99518b6ec0cd098a9dc2b76aca93eae5818d542af8c1921378 |
|
MD5 | 4a671ff8c1b8f611c3dddb4c3c673070 |
|
BLAKE2b-256 | 0d82ae3bb748ebcf16aa8e0d939bc751ef011daa479b5e24123695eb63d94c95 |