Database Wrapper

The Peewee database wrapper provides a thin layer of integration between flask apps and the peewee orm.

The database wrapper is important because it ensures that a database connection is created for every incoming request, and closed upon request completion. It also provides a subclass of Model which works with the database specified in your app’s configuration.

Most features of flask-peewee require a database wrapper.

The database wrapper reads its configuration from the Flask application. The configuration requires only two arguments, but any additional arguments will be passed to the database class:

name

The name of the database to connect to (or filename if using sqlite3)

engine

The import path of the database class, which must be a subclass of peewee.Database.

from flask import Flask
from peewee import *

from flask_peewee.db import Database

DATABASE = {
    'name': 'example.db',
    'engine': 'peewee.SqliteDatabase',
}

app = Flask(__name__)
app.config.from_object(__name__)  # Load database configuration from module.

# Instantiate the db wrapper.
db = Database(app)

# Start creating models.
class Blog(db.Model):
    name = CharField()
    # .. etc.

The configuration may instead be a database URL. Any scheme supported by playhouse.db_url works:

DATABASE = 'sqlite:///example.db'

You can also directly pass the Peewee database instance to the Database helper:

app = Flask(__name__)
app.config.from_object(__name__)

sqlite_db = SqliteDatabase('example.db')
db = Database(app, sqlite_db)

class Blog(db.Model):
    name = CharField()  # ...

The database initialization can be deferred to support more dynamic behavior:

from flask_peewee.db import Database

# Defer initialization but define our models.
db = Database()

class Blog(db.Model):
    name = CharField()
    # .. etc.

# Some time later, we can:
app = Flask(__name__)
app.config.from_object(__name__)
db.init_app(app)

# Or we can also specify the database directly.
app = Flask(__name__)

sqlite_db = SqliteDatabase('example.db')
db.init_app(app, sqlite_db)

Other examples

Connection pooled Postgres or MySQL:

DATABASE = {
    'name': 'my_app',
    'engine': 'playhouse.pool.PooledPostgresqlDatabase',
    # 'engine': 'playhouse.pool.PooledMySQLDatabase',
    # 'user': 'postgres',
    # 'password': 'secret password',
    # 'host': '127.0.0.1',
}

To connect to Postgres / MySQL without pool:

DATABASE = {
    'name': 'my_database',
    'engine': 'peewee.PostgresqlDatabase',
    # 'engine': 'peewee.MySQLDatabase',
    'user': 'db_user',
    'password': 'secret password',
}