Working with multiple databases from the same class model

Asked

Viewed 381 times

0

I am new in Python and I need to implement a solution that every system user should have a separate database, briefly what I need is something like

db1 = Persistencia('mysql', 'usuario','minhasenha', '192.168.0.1','banco1')    
db2 = Persistencia('mysql', 'usuario','minhasenha', '192.168.0.1','banco2')    

#mapeia os models para o banco de dados
db1.mapeiaModels([Pessoa, Contato])
db2.mapeiaModels([Pessoa, Contato])

#atualiza a estrutura do banco de acordo com o mapeamento, 
#adiciona ou altera colunas NUNCA apaga colunas
db1.sync() 

pessoa = Pessoa()
pessoa.nome = 'RODRIGO'
pessoa.telefone = '88888888'

db1.save(pessoa) #salva no banco de dados 1
db2.save(pessoa) #salva no banco de dados 2

I need to have this code-level control, logically I don’t want to develop an ORM, I just want to do a wrapper from one of the already existing ORM frameworks, I took a look at Django, Pypone and Sqlalchemy, but couldn’t identify how I can create my class there Persistencia using "under the table" one of these Orms and he gave me this flexibility, as I said, I’m new to python and I don’t know these frameworks well, some hint?

Note: I need to use on the same server databases separated as shown in the example, in the case banco1 and banco2 and it is crucial to update the scheme with minimal effort, that is, the framework that will be used should have this "Feature"

  • Specify more your problem. What you actually tried?

  • What I want is to know if some of the Orms would be able to create several connections with different databases with the same class structure, because in my case each client of the system I need to create a database for it, all this automatically clear, the ORM being able to do this I would do this class there just to facilitate the use and behind would use the ORM, I did not know if I had how to do or how to do, but I just found this tutorial here [http://www.pythoncentral.io/introductory-tutorial-python-sqlalchemy/] and I see I can do it! thank you!

  • 1

    I don’t understand why the -1!

1 answer

0


You have some options how to do this if you use Django you can use the models yourself, otherwise the most popular ORM for python is the Sqlalchemy.

Using Sqlalchemy you can create multiple connections:

engine1 = create_engine('sqlite:///example1.db')
engine2 = create_engine('sqlite:///example2.db')

And take advantage of the same models just taking care of the time that effective querys with the models use the Session regarding the correct connection.

  • Look, initially by the comment I had succeeded with the Sqlalchemy but then I switched to the same Django and saw that he can do it quietly, thanks for the reply, I will put as accepted, valeww!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.