Skip to main content

Flask-SQLORM

Flask integration for sqlorm

Setup

Install:

$ pip install flask-sqlorm

Setup:

from flask import Flask
from flask_sqlorm import FlaskSQLORM

app = Flask()
db = FlaskSQLORM(app, "sqlite://:memory:")

Usage

All exports from the sqlorm package are available from the extension instance.

Define some models:

class Task(db.Model):
    id: db.PrimaryKey[int]
    title: str
    done: bool = db.Column(default=False)

A session is automatically started everytime an app context is created. Perform queries directly in your endpoints:

@app.route("/tasks")
def list_tasks():
    tasks = Task.find_all()
    return render_template("tasks.html", tasks=tasks)

The session is rollbacked at the end of the request.

To commit some data, start a transaction using the db object:

@app.route("/tasks", methods=["POST"])
def create_task():
    with db:
        task = Task.create(title=request.form["title"])
    return render_template("task.html", task=task)

The current session is available using db.session

Additional utilities provided by Flask-SQLORM

Model classes have the additional methods:

  • find_one_or_404: same as find_one but throw a 404 when no results are returned
  • get_or_404: same as get but throw a 404 when no results are returned

Managing the schema

Some CLI commands are available under the db command group. Check out flask db --help for a list of subcommands.

SQLite defaults

If using an SQLite database, the following settings will be applied:

  • foreign_keys are ON
  • fine tuning for web workloads
  • the database directory will be created if missing

These settings are provided by the SQLORM SQLite driver.

Configuration

Configure the sqlorm engine using the extension's constructor or init_app(). Configuration of the engine is performed using the URI method. Additional engine parameters can be provided as keyword arguments.

Configuration can also be provided via the app config under the SQLORM_ namespace. Use SQLORM_URI to define the database URI.

Using multiple engines

You can setup multiple engines via the config and use an EngineDispatcher to select an engine to use.

db = FlaskSQLORM(app, "sqlite://:memory:", alt_engines=[{"uri": "sqlite://:memory", "tags": ["readonly"]}])

with db.engines.readonly:
    # Execute on an engine randomly selected from the one matching the readonly tag

with db.engines:
    # Uses the default engine

The context can be used inside other contexts:

@app.route()
def endpoint():
    objs = MyModel.find_all() # uses the default engine (in a non commit transaction)

    with db.engines.master: # uses a random engine matching the master tag (in a committed transaction)
        obj = MyModel.create()

    with db.engines.readonly.session(): # uses a random engine matching the readonly tag (in a non commit transaction)
        objs = MyModel.find_all()

You can create more advanced use case by subclassing EngineDispatcher. For example, to implement selection based on an http header that can be set by a load balancer to use the closest geographic replica. And use the primary server for write.

from sqlorm import EngineDispatcher

class HeaderEngineDispatcher(EngineDispatcher):
    def select_all(self, tag=None):
        if not tag and self.header and has_request_context() and self.header in request.headers:
            return self.select_all(request.headers[self.header])
        return super().select_all(tag)

db = FlaskSQLORM(app, "postgresql://primary", engine_dispatcher_class=HeaderEngineDispatcher,
                 alt_engines=[{"uri": "postresql://replica1", "tags": ["usa"]},
                              {"uri": "postresql://replica2", "tags": ["europe"]}])

@app.route()
def endpoint():
    MyModel.find_all() # execute on engine selected via header
    with db:
        MyModel.create() # execute on default engine

Metadata

Release files for flask-sqlorm 0.3.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flask-sqlorm 0.3.2
File Size Uploaded
flask_sqlorm-0.3.2.tar.gz 4.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for flask-sqlorm 0.3.2
File Interpreter ABI Platform
flask_sqlorm-0.3.2-py3-none-any.whl Python 3 none any Details

Total release size: 10.1 kB

Release files / flask_sqlorm-0.3.2.tar.gz

Download URL flask_sqlorm-0.3.2.tar.gz
Size 4.6 kB
Tags Source
SHA-256 checksum
How to use checksums
3376f5e28f12a3833f241a7e5d54b439572db744df5f1dfc83afefca7b5379e0
BLAKE2b-256 checksum
How to use checksums
cd2057c914c677bc65aa94f484f3aba1bfc3f2283d299e1c897a4a2b0045c546
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.9 {"installer":{"name":"uv","version":"0.9.9"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / flask_sqlorm-0.3.2-py3-none-any.whl

Download URL flask_sqlorm-0.3.2-py3-none-any.whl
Size 5.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3bb7a085caae40cdaad788fef4b2bc1b66d0a1f4c5710455a4c8b8b39994ca48
BLAKE2b-256 checksum
How to use checksums
84e329a98c7eb9f5780265dcb612a96ebcf20b23d19cc01a208b7f1082d80a1f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.9 {"installer":{"name":"uv","version":"0.9.9"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release history Release notifications | RSS feed

This release

0.3.2 This release

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page