English 中文(简体)
Peewee - Defining Database Dynamically
  • 时间:2024-11-03

Peewee - Defining Database Dynamically


Previous Page Next Page  

If your database is scheduled to vary at run-time, use DatabaseProxy helper to have better control over how you initiapse it. The DatabaseProxy object is a placeholder with the help of which database can be selected in run-time.

In the following example, an appropriate database is selected depending on the apppcation’s configuration setting.


from peewee import *
db_proxy = DatabaseProxy() # Create a proxy for our db.

class MyUser (Model):
   name=TextField()
   city=TextField(constraints=[SQL("DEFAULT  Mumbai ")])
   age=IntegerField()
   class Meta:
      database=db_proxy
      db_table= MyUser 

# Based on configuration, use a different database.
if app.config[ TESTING ]:
   db = SqpteDatabase( :memory: )
epf app.config[ DEBUG ]:
   db = SqpteDatabase( mydatabase.db )
else:
   db = PostgresqlDatabase(
       mydatabase , host= localhost , port=5432, user= postgres , password= postgres 
   )

# Configure our proxy to use the db we specified in config.
db_proxy.initiapze(db)
db.connect()
db.create_tables([MyUser])

You can also associate models to any database object during run-time using bind() method declared in both database class and model class.

Following example uses bind() method in database class.


from peewee import *

class MyUser (Model):
   name=TextField()
   city=TextField(constraints=[SQL("DEFAULT  Mumbai ")])
   age=IntegerField()

db = MySQLDatabase( mydatabase , host= localhost , port=3306, user= root , password=  )
db.connect()
db.bind([MyUser])
db.create_tables([MyUser])

The same bind() method is also defined in Model class.


from peewee import *

class MyUser (Model):
   name=TextField()
   city=TextField(constraints=[SQL("DEFAULT  Mumbai ")])
   age=IntegerField()

db = MySQLDatabase( mydatabase , host= localhost , port=3306, user= root , password=  )
db.connect()
MyUser.bind(db)
db.create_tables([MyUser])
Advertisements