mrQWERTY
mrQWERTY

Reputation: 4149

Python, best practices importing config file

I am creating a Flask web application and I have a file storing some configurations. However, some of the inner modules would need to refer to the config.py which lies two directories above. I am using relative imports which I think is a bad practice and is not flexible.

Structure:

workspace:
    app:
      database:
         __init__.py
         database.py
    config.py

In my database.py file, I am importing config as import ...config. Is there a better way?

Upvotes: 3

Views: 7572

Answers (2)

franklin
franklin

Reputation: 1819

You should check out how config is managed in Flasky. Basically, config.py resides in the application root, just like in your project.

Then in your app folder you initiate the application as a package, i.e., by adding the __init__.py file.

__init__.py contains an import statement to your config:

from config import config

Then you can use Flask blueprints to initiate calls to your config. Also take a look at how larger applications are managed in Flask.

All in all, it will require about four changes to your existing source:

  1. Make your application a package by creating the __init__.py file.
  2. Add the import statement to __init__.py in your root app directory.
  3. In your module directory (in this case database/) create an __init__.py file to allow that module to be used as a blueprint in your larger flask application. [Note in this case module refers to a modularized part of your application; not to a python module; confusing I know.]
  4. Back in app/__init__.py import the blueprint, i.e.,
from .database import database as db_blueprint
app.register_blueprint(db_blueprint)

It's a bit of leg work but it's really great if your interested in writing more complex applications and (of course) organizing your projects.

Upvotes: 1

Wolph
Wolph

Reputation: 80031

Generally I'd recommend module level imports in cases like these, so something along the lines of from application import config Since your config.py is in a bare directory that's not really possible of course... unless you move the config.py to some place within your app.

An alternative solution might be to create a class/app that manages your configuration so you always have it available.

Having that said, I'm sure I understand the need for this config file. Flask handles configuration for you automatically right? Simply import your app and use app.config to get your configuration.

Upvotes: 0

Related Questions