Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

peewee - Define models separately from Database() initialization

I need to use some ORM engine, like peewee, for handling SQLite database within my python application. However, most of such libraries offer syntax like this to define models.py:

import peewee

db = peewee.Database('hello.sqlite')

class Person(peewee.Model):
    name = peewee.CharField()

    class Meta:
        database = db

However, in my application, i cannot use such syntax since database file name is provided by outside code after import, from module, which imports my models.py.

How to initialize models from outside of their definition knowing dynamic database file name? Ideally, models.py should not contain "database" mentions at all, like normal ORM.

like image 601
Croll Avatar asked Sep 08 '16 15:09

Croll


People also ask

What is Peewee database?

Peewee is a Python Object Relational Mapping (ORM) library which was developed by a U.S. based software engineer Charles Leifer in October 2010. Its latest version is 3.13. 3. Peewee supports SQLite, MySQL, PostgreSQL and Cockroach databases.

How do I use peewee in Python?

When starting a project with peewee, it's typically best to begin with your data model, by defining one or more Model classes: from peewee import * db = SqliteDatabase('people. db') class Person(Model): name = CharField() birthday = DateField() class Meta: database = db # This model uses the "people.

What is Peewee Python?

Peewee is a Python ORM (Object-Relational Mapping) library which supports SQLite, MySQL, PostgreSQL and Cockroach databases.

Is peewee thread safe?

Peewee keeps track of the connection state using thread-local storage, making the Peewee Database object safe to use with multiple threads. Each thread will have it's own connection, and as a result any given thread will only have a single connection open at a given time.


1 Answers

Maybe you are looking at proxy feature : proxy - peewee

database_proxy = Proxy()  # Create a proxy for our db.

class BaseModel(Model):
    class Meta:
        database = database_proxy  # Use proxy for our DB.

class User(BaseModel):
    username = CharField()

# Based on configuration, use a different database.
if app.config['DEBUG']:
    database = SqliteDatabase('local.db')
elif app.config['TESTING']:
    database = SqliteDatabase(':memory:')
else:
    database = PostgresqlDatabase('mega_production_db')

# Configure our proxy to use the db we specified in config.
database_proxy.initialize(database)
like image 103
MrPandav Avatar answered Sep 17 '22 22:09

MrPandav