Database

The Peewee Database object represents a connection to a database. The Database class is instantiated with all the information needed to open a connection to a database, and then can be used to:

  • Open and close connections.
  • Execute queries.
  • Manage transactions (and savepoints).
  • Introspect tables, columns, indexes, and constraints.

Peewee comes with support for SQLite, MySQL and Postgres. Each database class provides some basic, database-specific configuration options.

  1. from peewee import *
  2. # SQLite database using WAL journal mode and 64MB cache.
  3. sqlite_db = SqliteDatabase('/path/to/app.db', pragmas={
  4. 'journal_mode': 'wal',
  5. 'cache_size': -1024 * 64})
  6. # Connect to a MySQL database on network.
  7. mysql_db = MySQLDatabase('my_app', user='app', password='db_password',
  8. host='10.1.0.8', port=3316)
  9. # Connect to a Postgres database.
  10. pg_db = PostgresqlDatabase('my_app', user='postgres', password='secret',
  11. host='10.1.0.9', port=5432)

Peewee provides advanced support for SQLite and Postgres via database-specific extension modules. To use the extended-functionality, import the appropriate database-specific module and use the database class provided:

  1. from playhouse.sqlite_ext import SqliteExtDatabase
  2. # Use SQLite (will register a REGEXP function and set busy timeout to 3s).
  3. db = SqliteExtDatabase('/path/to/app.db', regexp_function=True, timeout=3,
  4. pragmas={'journal_mode': 'wal'})
  5. from playhouse.postgres_ext import PostgresqlExtDatabase
  6. # Use Postgres (and register hstore extension).
  7. db = PostgresqlExtDatabase('my_app', user='postgres', register_hstore=True)

For more information on database extensions, see: