R
R
rosperitus2014-08-23 15:56:14
Python
rosperitus, 2014-08-23 15:56:14

Using one Peewee model (ORM) for many databases?

Tell me how you can use certain Peewee models on several Sqlite databases (not through a standard module, but through APSW). Many databases will be with the same structure (3 tables, and 100k records).
The method with peewee.Proxy() did not work (you need to initialize each time).
Example with peewee.Proxy()

# -*- coding: utf-8 -*-

import peewee
from playhouse.apsw_ext import APSWDatabase

# Создаем прокси
database_proxy = peewee.Proxy()

class BaseModel(peewee.Model):
    # Объявляем прокси вместо базы данных
    class Meta:
        database = database_proxy

class Simple(BaseModel):
    name = peewee.CharField()

# БД №1
database1 = APSWDatabase('E:/Temp/simple1.db')
# БД №2
database2 = APSWDatabase('E:/Temp/simple2.db')

# Инициализируем прокси для БД №1
database_proxy.initialize(database1)
try:
# try потому что, APSW ругается на создание таблицы, 
# которая уже существует (игнорирует safe=True)
    database1.create_tables([Simple], safe=True)
except:
    pass

Simple.create(name='name1')
# Инициализируем прокси для БД №2
database_proxy.initialize(database2)
try:
    database2.create_tables([Simple], safe=True)
except:
    pass
Simple.create(name='name2')

database1.close()
database2.close()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question