Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically set the SQLite database file in Peewee?

Tags:

peewee

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?

like image 984
Christopher Shroba Avatar asked Dec 23 '16 17:12

Christopher Shroba


People also ask

Can SQLite store an entire database in a single file?

Afaik, SQLite stores a single database in a single file.

What is Peewee database?

The Peewee Database object represents a connection to a database. The Database class is instantiated with all the information needed to open a connection to a database, and then can be used to: Open and close connections. Execute queries.

Where SQLite files are stored?

The Android SDK provides dedicated APIs that allow developers to use SQLite databases in their applications. The SQLite files are generally stored on the internal storage under /data/data/<packageName>/databases.


1 Answers

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)
like image 193
sterling baldwin Avatar answered Oct 23 '22 18:10

sterling baldwin