Skip to main content

SQLAlchemy Core integration for Flask

Project description

SQLAlchemy Core integration for Flask application.

Provides an easy way for setting up and using SQLAlchemy Core in Flask (or Werkzeug-based, really) applications.

The main benefit of using this package over plain SQLAlchemy is the ability of sharing the current connection in a context-local “global” object.

This allows creating nested transactions without having to explicitly pass the connection object across functions.

This in turn enables running test functions inside a transaction, which will be rolled back on test teardown, greatly reducing test run time, by removing the need of continuously dropping and re-creating the whole database schema for each test function run.

Usage

Set up

import os
from flask_sqlalchemy_core import FlaskSQLAlchemy

DATABASE_URL = os.environ['DATABASE_URL']

db = FlaskSQLAlchemy(DATABASE_URL)

Running queries

from sqlalchemy import select

# Create your query here
query = select(...)

with db.connect() as conn:
    result = conn.execute(query)
    # Do something with the result...

Transactions

with db.transaction() as conn:
    result = conn.execute(query)

The transaction will automatically committed upon a successful exit from the “with” block, or rolled back if an exception was raised.

Nested transactions

Simply nest with db.transaction(): blocks.

This allows for more reusable code, for example:

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)

Define tables

Just do as you normally would (create a Metadata instance, use it to define your schema).

Creating schema

metadata.create_all(db.get_engine())

Test fixtures

For use with pytest, place those in a conftest.py file in your tests directory.

Note: you might want to change your DATABASE_URL environment variable during testing, to avoid overriding your current development database.

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)

Database migrations

Use Alembic for creating database migrations.

Database support

The library is currently tested with PostgreSQL (10).

Everything should work with other backends too (except nested transactions, on backends that don’t support checkpoints).

Testing

Before running the test suite, you’ll need to start a SQL database and set the DATABASE_URL environment variable.

For convenience, you can use the bin/run-test-database script, which will automatically run a PostgreSQL instance via Docker.

The script will print a suitable value for DATABASE_URL as well.

Oncer you’re done, simply kill it via Ctrl-C.

To install test dependencies:

pip install -r test_requirements.txt

To run the test suite:

pytest -vvv ./tests

To run tests using SQLite backend:

DATABASE_URL="sqlite:///:memory:" pytest -vvv ./tests

Warning: some tests will be skipped, as SQLite doesn’t support nested transactions.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flask_sqlalchemy_core-0.1.tar.gz (5.5 kB view details)

Uploaded Source

Built Distribution

flask_sqlalchemy_core-0.1-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

Details for the file flask_sqlalchemy_core-0.1.tar.gz.

File metadata

  • Download URL: flask_sqlalchemy_core-0.1.tar.gz
  • Upload date:
  • Size: 5.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.19.1 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.26.0 CPython/3.7.0

File hashes

Hashes for flask_sqlalchemy_core-0.1.tar.gz
Algorithm Hash digest
SHA256 b6868aee88e674f25c44c84662f76d58c786ffa06062a0b37cf91892229c5b95
MD5 c4b7b3bd9610da32c6dd8b3739c8e74a
BLAKE2b-256 46752f8a1d171e023ce1ba76467eddfde808116e761b33fb16a38764a6a87dd0

See more details on using hashes here.

File details

Details for the file flask_sqlalchemy_core-0.1-py3-none-any.whl.

File metadata

  • Download URL: flask_sqlalchemy_core-0.1-py3-none-any.whl
  • Upload date:
  • Size: 6.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.19.1 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.26.0 CPython/3.7.0

File hashes

Hashes for flask_sqlalchemy_core-0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 007df2da8b0dac24af95589c8fff841fb07bdbb1a77febfad23c1ac9b0071ed0
MD5 b6877e825545ffc1db0e05a5d525f4da
BLAKE2b-256 d56d304870191339b63f28455bd493a1e0de771666e3dec14671d9d04c6d325c

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page