Skip to main content

Flask integration for sqlorm

Project description

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

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_sqlorm-0.3.1.tar.gz (4.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flask_sqlorm-0.3.1-py3-none-any.whl (5.1 kB view details)

Uploaded Python 3

File details

Details for the file flask_sqlorm-0.3.1.tar.gz.

File metadata

  • Download URL: flask_sqlorm-0.3.1.tar.gz
  • Upload date:
  • Size: 4.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.17

File hashes

Hashes for flask_sqlorm-0.3.1.tar.gz
Algorithm Hash digest
SHA256 d39d876f578d41c43e775b5c731b25df6a4c90ef9996ffc91d19c925b1911537
MD5 dc8eacd02232d0b687e83b3521a7925e
BLAKE2b-256 751ea9072bab2441c251c89abd8560f5d2533d3840cb32564a27d9104663b8ab

See more details on using hashes here.

File details

Details for the file flask_sqlorm-0.3.1-py3-none-any.whl.

File metadata

File hashes

Hashes for flask_sqlorm-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a3bd34306bad724d4661e4441d30ad37d2c06f97babbf32fe59fec5ce792b6c4
MD5 7e1035d9d4972f9ee2f8f9a8a044db2b
BLAKE2b-256 c3b778668ce09ba749c043b5e2986d0a4b81de16bb1062211d7e347e21e0428f

See more details on using hashes here.

Supported by

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