0

I have a module models.py with some data logic:

db = PostgresqlDatabase(database='database', user='user')

# models logic

and flask app which actually interacts with database:

from models import db, User, ...

But I want to move initializing all setting from one config file in flask app:

So I could separate importing db from other stuff (I need this for access to module variable db in models):

import models
from models import User, ...
app.config.from_object(os.environ['APP_SETTINGS'])
models.db = PostgresqlDatabase(database=app.config['db'],
                               user=app.config['db'])

and use further db as models.db

But seems it is kinda ugly. Duplicating imports, different usage of module stuff..

Is there any better way how to handle this situation?

xiº
  • 4,605
  • 3
  • 28
  • 39
  • `from somewhere import db` is terrible -- it means db can never be reinitialised, thus your app cannot change config on the fly. It also makes unit-testing much harder, you end up mocking out same db in many modules. – Dima Tisnek Mar 21 '16 at 07:57

1 Answers1

0

I'd recommend 1 level of indirection, so that your code becomes like this:

import const
import runtime

def foo():
    runtime.db.execute("SELECT ... LIMIT ?", (..., const.MAX_ROWS))

You get:

  • clear separation of leaf module const
  • mocking and/or reloading is possible
  • uniform and concise access in all user modules

To get rich API on runtime, use the "replace module with object at import" trick ( see __getattr__ on a module )

Community
  • 1
  • 1
Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120