Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to setup a flask application which runs on Python 3.7.x. I've referenced many tutorials online but can't seem to resolve this ModuleNotFoundError and none of the stackoverflow questions are related.

Below is my project structure:

project/
    app/
        __init__.py
        api.py
        conf.py
        models.py
        schema.py
    orders-mgmt.toml
    requirements.txt
    README.md
# app/__init__.py

from flask import Flask
from flask_restful import Api
from app.conf import load_from_toml
import logging
import os.path

if os.path.isfile('/opt/project/orders-mgmt.toml'):
    config = load_from_toml('/opt/project/orders-mgmt.toml')
else:
    config = load_from_toml()

app = Flask(__name__)
api = Api(app)

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = config['mysql']['db_uri']
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
    'pool_recycle': 3000,
    'pool_pre_ping': True,
}
# app/api.py

from flask import jsonify
from flask_restful import Resource
from flask_sqlalchemy import SQLAlchemy
from app import app, api, config #ERROR here
from app.models import Request
from app.schema import RequestSchema

db = SQLAlchemy(app)


class TestGet(Resource):

    def get(self):
        return 'okay'


api.add_resource(TestGet, '/')

if __name__ == '__main__':
    app.run(debug=True, host='localhost', port=5000)

I'm getting the ModuleNotFoundError in app/api.py line from app import app, api, config when I run python app/api.py:

$ python app/api.py
Traceback (most recent call last):
  File "app/api.py", line 4, in <module>
    from app import app, api, config
ModuleNotFoundError: No module named 'app'

May I know what is the issue here with my flask application?

question from:https://stackoverflow.com/questions/65936260/modulenotfounderror-cannot-import-from-app-init-py

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
331 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have circular dependency issue Your app will not work in such files structure Remove logic from init module to another one OR you'll need to remove all absolute imports(imports for your own modules) and replace them with relative

for __init__ module

replace this line:

from app.conf import load_from_toml

with


from .conf import load_from_toml

for app module

replace these lines:

from app import app, api, config #ERROR here
from app.models import Request
from app.schema import RequestSchema

with

from . import app, api, config
from .models import Request
from .schema import RequestSchema

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...