Connecting using a Database URL

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

Example code:

  1. import os
  2.  
  3. from peewee import *
  4. from playhouse.db_url import connect
  5.  
  6. # Connect to the database URL defined in the environment, falling
  7. # back to a local Sqlite database if no database URL is specified.
  8. db = connect(os.environ.get('DATABASE') or 'sqlite:///default.db')
  9.  
  10. class BaseModel(Model):
  11. class Meta:
  12. 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/mydb will create a MySQLDatabase instance for the local MySQL database _my_db.
  • More examples in the db_url documentation.