12

I'm using Peewee for a project I'm working on, and I'm trying to figure out how to dynamically set the database so that I can use one for production and one for testing. All the examples I've seen have the following line outside of any class:

database = SqliteDatabase(DATABASE)

which I find strange, since I would think that you would want that to be in a class so you could pass in different database paths. Any suggestions for choosing one database for prod and another for testing?

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Christopher Shroba
  • 7,006
  • 8
  • 40
  • 68

2 Answers2

10

I just came across a similar issue, here's how I solved it to define the path to the database at run time:

Models file:

import peewee

database = peewee.SqliteDatabase(None)  # Defer initialization

class SomeData(peewee.Model):
    somefield = peewee.CharField()

    class Meta:
        database = database

Then in the class that uses the database:

from models import SomeData

class DatabaseUser:
    def __init__(self, db_path):
        database.init(db_path)
Asclepius
  • 57,944
  • 17
  • 167
  • 143
4

The database is typically declared at module scope because the model classes are defined there, and they typically depend on the database.

However, you can defer the initialization of your database using these techniques:

The first is useful if you are using the same database class. You really only need the Proxy when you're using Sqlite for dev and Postgres for prod, e.g.

coleifer
  • 24,887
  • 6
  • 60
  • 75
  • 1
    in your referenced documentation for "Run time db config" when using two separate SQLite databases for testing and production, where is the database.init(database_name) method called when there are separate test.py for testing and main.py file or production but the actual "database" variable is defined in the models.py file? – Declan Apr 04 '18 at 03:40