Answer the question
In order to leave comments, you need to log in
How to implement simultaneous connection of a peewee model to several databases?
Reading the peewee help, I was struck by the way the database connection was set: through the built-in metadata class inside the base model. Those. A model can only have ONE connection to the database at a time.
Now let's imagine a very real scenario. There is an application in production using a module with a data model. I want to run tests with new functionality using the same model (the base, of course, is different - the test one). It turns out that it is fundamentally impossible to do this, since our module can work with only one connection. I understand correctly? Is there a nice and easy way to get around this limitation?
Answer the question
In order to leave comments, you need to log in
Proxy - peewee API#Proxy
Continuing the theme, if it's dirty to emulate the work of django:
# -*- coding: utf-8 -*-
import peewee
db = peewee.Proxy()
first = peewee.SqliteDatabase('first.db')
second = peewee.SqliteDatabase('second.db')
class Test(peewee.Model):
name = peewee.CharField()
class Meta:
database = db
db_table = 'test'
@classmethod
def using(cls, db):
cls._meta.database.initialize(db)
return cls
db.initialize(first)
Test.create_table(fail_silently=True)
db.initialize(second)
Test.create_table(fail_silently=True)
Test.using(first).create(name='Test1') # Переключились на first
Test.create(name='Test2') # Используется ранее переключенная база first
Test.using(second).create(name='Test3') # Переключились на secong
Test.create(name='Test4') # Пишется в second
Test.using(first).create(name='Test5')
print ','.join([x.name for x in Test.using(first).select()])
# Test1,Test2,Test5
print ','.join([x.name for x in Test.using(second).select()])
# Test3,Test4
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question