Connecting using a Database URL

The playhouse module Database URL provides a helper connect() function that accepts a database URL and returns a Database instance.

Example code:

  1. import os
  2. from peewee import *
  3. from playhouse.db_url import connect
  4. # Connect to the database URL defined in the environment, falling
  5. # back to a local Sqlite database if no database URL is specified.
  6. db = connect(os.environ.get('DATABASE') or 'sqlite:///default.db')
  7. class BaseModel(Model):
  8. class Meta:
  9. database = db

Example database URLs:

  • sqlite:///my_database.db will create a SqliteDatabase instance for the file my_database.db in the current directory.
  • sqlite:///:memory: will create an in-memory SqliteDatabase instance.
  • postgresql://postgres:my_password@localhost:5432/my_database will create a PostgresqlDatabase instance. A username and password are provided, as well as the host and port to connect to.
  • mysql://user:passwd@ip:port/my_db will create a MySQLDatabase instance for the local MySQL database my_db.
  • More examples in the db_url documentation.