Skip to main content

The Python database micropackage

Project description

fort

The Python database micropackage


fort is a thin database wrapper for programmers who love to write SQL. Use it when SQLAlchemy is too much.

Usage

Start by initializing an object for your database, providing a connection string:

import fort

db = fort.PostgresDatabase('postgres://user:password@host/database')

Each of fort's database classes provides a small set of methods that makes working with SQL simple. You can immediately begin making queries to the database:

import uuid

db.u('CREATE TABLE widgets (id uuid PRIMARY KEY, name text)')

my_id = uuid.uuid4()
db.u('INSERT INTO widgets (id, name) VALUES (%(id)s, %(name)s)', {'id': my_id, 'name': 'Thingy'})

for row in db.q('SELECT id, name FROM widgets'):
    print(row['id'], row['name'])

my_widget = db.q_one('SELECT id, name FROM widgets WHERE id = %(id)s', {'id': my_id})
print(my_widget['name'])

my_widget_name = db.q_val('SELECT name FROM widgets WHERE id = %(id)s', {'id': my_id})
print(my_id, my_widget_name)

Using one of fort's database classes directly is fine, but it is better to consolidate your SQL statements by subclassing one of fort's classes and adding your own methods:

class MyDatabase(fort.PostgresDatabase):

    def migrate(self):
        self.u('CREATE TABLE widgets (id uuid PRIMARY KEY, name text)')

    def add_widget(self, widget_name: str) -> uuid.UUID:
        new_id = uuid.uuid4()
        sql = 'INSERT INTO widgets (id, name) VALUES (%(id)s, %(name)s)'
        params = {'id': new_id, 'name': widget_name}
        self.u(sql, params)
        return new_id

    def list_widgets(self) -> List[Dict]:
        return self.q('SELECT id, name FROM widgets')

    def get_widget(self, widget_id: uuid.UUID) -> Optional[Dict]:
        sql = 'SELECT id, name FROM widgets WHERE id = %(id)s'
        return self.q_one(sql, {'id': widget_id})

    def get_widget_name(self, widget_id: uuid.UUID) -> Optional[str]:
        sql = 'SELECT name FROM widgets WHERE id = %(id)s'
        return self.q_val(sql, {'id': widget_id})

db = MyDatabase('postgres://user:password@host/database')
db.migrate()

my_id = db.add_widget('Thingy')

for widget in db.list_widgets():
    print(widget['id'], widget['name'])

my_widget = db.get_widget(my_id)
print(my_widget['id'], my_widget['name'])

my_widget_name = db.get_widget_name(my_id)
print(my_id, my_widget_name)

Database class methods

The following methods come with every fort database class:

def u(self, sql: str, params: Dict = None) -> int: ...
    """
    Execute a statement and return the number of rows affected.
    Use this method for CREATE, INSERT, and UPDATE statements.
    """

def q(self, sql: str, params: Dict = None) -> List[Dict]: ...
    """
    Execute a statement and return all results.
    Use this method for SELECT statements.
    """

def q_one(self, sql: str, params: Dict = None) -> Optional[Dict]: ...
    """
    Execute a statement and return the first result.
    If there are no results, return `None`.
    """

def q_val(self, sql: str, params: Dict = None) -> Any: ...
    """
    Execute a statement and return the value in the first column of the first result.
    If there are no results, return `None`.
    """

Each fort database class instance also has a logger at self.log:

    db = MyDatabase('postgres://user:password@host/database')
    db.log.info('Hello from my database class instance!')

Notes on specific database classes

PostgresDatabase

Use PostgresDatabase to connect to a PostgreSQL database. Use pyformat paramstyle for all your statements. Your connection string will be passed directly to psycopg2.connect().

You are still responsible for installing psycopg2.

SQLiteDatabase

Use SQLiteDatabase to connect to an SQLite database. Use named paramstyle for all your statements. Your connection string will be passed directly to sqlite3.connect().

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

fort-2025.0.tar.gz (4.5 kB view details)

Uploaded Source

Built Distribution

fort-2025.0-py3-none-any.whl (5.3 kB view details)

Uploaded Python 3

File details

Details for the file fort-2025.0.tar.gz.

File metadata

  • Download URL: fort-2025.0.tar.gz
  • Upload date:
  • Size: 4.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.7.1

File hashes

Hashes for fort-2025.0.tar.gz
Algorithm Hash digest
SHA256 04c8c8d19a56b4e04686d817b1b5c56d1f99e9cb92104fcfaadc0281d0ec41b4
MD5 b17840066f247209494e6c762831d1ea
BLAKE2b-256 0f3544ea08da29f19bf0f78048309449d35cf2799345b3ac25f5d63dfaea41e1

See more details on using hashes here.

File details

Details for the file fort-2025.0-py3-none-any.whl.

File metadata

  • Download URL: fort-2025.0-py3-none-any.whl
  • Upload date:
  • Size: 5.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.7.1

File hashes

Hashes for fort-2025.0-py3-none-any.whl
Algorithm Hash digest
SHA256 302a4fe2b7dcfdfdeb8cf60562271342569d9bf274eca6b01de4623c7e5eb3d0
MD5 4582f0108047baaee81cfb7f9ae2c152
BLAKE2b-256 2f023517c819352649ab13801368257fd6670a5b26d10fad01d9413e6ea2dba3

See more details on using hashes here.

Supported by

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