跳转到主要内容

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 (5.6 kB 查看哈希值)

上传时间: 源代码

构建分布

flask_sqlalchemy_core-0.1.1-py3-none-any.whl (6.2 kB 查看哈希值)

上传时间: Python 3

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面