Reputation: 103
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.
Upvotes: 3
Views: 8064
Reputation: 1956
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.
Upvotes: 3
Reputation: 5108
Try using absolute import. IMHO it makes things easier to grok
from __future__ import absolute_import
from application.config import production
This is absolute because you are specifying the exact path you are importing from which reduces ambiguity.
Also, you are missing __init__.py
in the application
folder
Upvotes: 4
Reputation: 14737
Assume you have config
in application/config/__init__.py
.
You also need __init__.py
under application
directory, if not, then the application/app
is your top level package, you can not access application/config
.
Upvotes: 1