ankur singh ankur singh - 1 year ago 185
Python Question

relative imports in python in flask app

I have read numerous SO questions and blogs. I am trying to structure my flask application. The current structure of my application is the following:

application
run_server.py
/config
__init__.py
production.py
staging.py
development.py
/app
__init__.py
/site
__init__.py
views.py


Now, inside
app/__init__.py
I want to access the config based on my environment( dev, staging, production).

from ..config import config


I am getting this error:


ValueError: Attempted relative import beyond toplevel package


I have tried using
-m
switch.
I have also tried to set
PYTHONPATH
as my root directory to tell interpreter what is top level package.
I think I am missing some fundamental in relative imports.

Answer Source

If you are running your application through run_server.py then there is no need of relative import in app/__init__.py. You can simply say,

from config import <production/staging/development>

This is because, when your interpreter interprets run_server.py, at the line say, from app import <something>, it will fetch app/__init__.py content and try to execute them at toplevel i.e. from directory application.

Now, assume you are running from ..config import config at toplevel. Obviously, it will throw an error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download