Database URL

This module contains a helper function to generate a database connection from a URL connection string.

connect(url, \*connect_params*)

Create a Database instance from the given connection URL.

Examples:

  • 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.
  • mysql+pool://user:passwd@ip:port/my_db?max_connections=20&stale_timeout=300 will create a PooledMySQLDatabase instance for the local MySQL database my_db with max_connections set to 20 and a stale_timeout setting of 300 seconds.

Supported schemes:

Usage:

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

parse(url)

Parse the information in the given URL into a dictionary containing database, host, port, user and/or password. Additional connection arguments can be passed in the URL query string.

If you are using a custom database class, you can use the parse() function to extract information from a URL which can then be passed in to your database object.

register_database(db_class, \names*)

Parameters:
  • db_class – A subclass of Database.
  • names – A list of names to use as the scheme in the URL, e.g. ‘sqlite’ or ‘firebird’

Register additional database class under the specified names. This function can be used to extend the connect() function to support additional schemes. Suppose you have a custom database class for Firebird named FirebirdDatabase.

  1. from playhouse.db_url import connect, register_database
  2. register_database(FirebirdDatabase, 'firebird')
  3. db = connect('firebird://my-firebird-db')