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:
import os
from peewee import *
from playhouse.db_url import connect
# Connect to the database URL defined in the environment, falling
# back to a local Sqlite database if no database URL is specified.
db = connect(os.environ.get('DATABASE') or 'sqlite:///default.db')
class BaseModel(Model):
class Meta:
database = db
Example database URLs:
sqlite:///my_database.db
will create aSqliteDatabase
instance for the filemy_database.db
in the current directory.sqlite:///:memory:
will create an in-memorySqliteDatabase
instance.postgresql://postgres:my_password@localhost:5432/my_database
will create aPostgresqlDatabase
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 aMySQLDatabase
instance for the local MySQL database my_db.- More examples in the db_url documentation.