I am working on a project in Flask and am having trouble with circular imports.
My app's structure looks like this:
.
├── api
│ ├── __init__.py
│ ├── schema.py
│ └── sender.py
├── app.py
├── config.py
├── README.md
├── run.sh
├── static
│ ├── css
│ │ ├── base.css
│ │ ├── index.css
│ │ └── model.css
│ └── index.html
├── templates
│ ├── base.html
│ ├── model.html
│ ├── schema_add.html
│ ├── schema.html
│ └── table.html
└── views
├── auth.py
├── error_handler.py
├── __init__.py
├── model.py
├── schema.py
└── table.py
The source code is available on this
Here's a trace of error:
Traceback (most recent call last):
File "./../anton_temp/app.py", line 3, in <module>
from views import *
File
"/home/shubham1172/Documents/Anton/anton_temp/views/__init__.py", line
16, in <module>
from .auth import *
File "/home/shubham1172/Documents/Anton/anton_temp/views/auth.py",
line 4, in <module>
from app import setConnection, getConnection, closeConnection
File "/home/shubham1172/Documents/Anton/anton_temp/app.py", line 4,
in <module>
from api import *
File "/home/shubham1172/Documents/Anton/anton_temp/api/__init__.py",
line 13, in <module>
from .schema import *
File "/home/shubham1172/Documents/Anton/anton_temp/api/schema.py",
line 5, in <module>
from app import getConnection
ImportError: cannot import name 'getConnection'
The problem is, I have to include my blueprints (views and api) in my app. The init file for these blueprints further include the py files which in turn has to include some functions from the app.
I read somewhere to include these functions in an external file, say extension.py and then call it from the blueprints, but my functions in app contains references to 'app' for its config object.
How do I fix this?
EDIT
As pointed out, I'll have to refactor my code. This shows an example of the same issue and the solution was given. However, the function in my extension would require a call to the app's config, i.e.
A.py
import B
from C import dependency
B.py
from C import dependency
C.py
def dependency():
#Use A.config here <----------
pass
Is there any way to solve this?
EDIT
I solved it by refactoring my code. I figured out that app.config can be exported to a different file with a simple function call.
C.py
obj = None
def setObj(object):
obj = object
def dependency():
#use obj now
pass
setObj(obj) can now be called from A.py!