In most of the cases, predefining the database if fine, as in the official Quickstart tutorial, following are the 2 major ways, database proxy and defining a database with None
parameter.
Database Proxy
# base_do.py mysql_config = { 'user': 'your_mysql_username', 'password': 'your_mysql_password', 'host': 'your_mysql_host', 'database': 'your_mysql_database' } db = MySQLDatabase(**mysql_config) class BaseDO(Model): class Meta: database = db
But there is a problem. If you have your config inside a JSON file, you have to load the json file in advance of importing the database ORM module, which could look like the following, and in this case, you are unable to change the config based on user input from argparse
. Having a statement before import is runnable, but it violates the PEP 8 style guide according toPEP 8: E402 module level import not at top of file
.
load_config_file('config/config.json') # The following import recursively imports the base_do module from audio_cleaner import api
To solve this problem, we can have a database proxy as a placeholder when the program initializes. And after importing the module and before using it, initialize it.
# base_do.py from peewee import Model, Proxy db_proxy = Proxy() class BaseDO(Model): class Meta: database = db_proxy
# populate_db.py from db.entity.menu_do import MenuDO from db.entity.review_do import ReviewDO from db.entity.user_do import UserDO from db.entity.outlet_do import OutletDO from peewee import MySQLDatabase from typing import Dict MODELS = [OutletDO, UserDO, ReviewDO, MenuDO] def populate_db(mysql_config: Dict[str, str], drop_exist: bool = False) -> None: db = MySQLDatabase(**mysql_config) db.bind(MODELS, bind_refs=False, bind_backrefs=False) db.connect() if drop_exist: db.drop_tables(MODELS) db.create_tables(MODELS)
if __name__ == '__main__': parser = argparse.ArgumentParser(description='Peewee Demo Parser') parser.add_argument('--host', dest='host', type=str, default='127.0.0.1', help='host for db') args = parser.parse_args() mysql_config.update({'host': args.host}) db_proxy.initialize(MySQLDatabase(**mysql_config)) populate_db(mysql_config, drop_exist=True) transform_outlet() transform_user() transform_review() transform_menu() app.run(host='0.0.0.0')
None
Parameter – Specify the details at run-time
# base_do.py db = MySQLDatabase(None)
# some_other_module.py # You may import the db variable from the db base module, then init it from base_do import db db.init(**mysql_config)