S
S
Semyon Prikhodko2014-05-22 14:24:07
Python
Semyon Prikhodko, 2014-05-22 14:24:07

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

1 answer(s)
L
LocNar, 2014-05-22
@ababo

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

In general, peewee is actively developing and constantly introducing new features, so you can write to him on github , it is quite possible that dirty hacks will not be needed in the next version.
Nevertheless, I still doubt the expediency of such behavior in general.
It is also possible that model aliases can have their own connections, but it is too lazy to read the resource or check it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question