ModuleNotFoundError using Flask

Question:

I’m trying to make a Flask api :

app.py
routes
-> __init__.py
-> myobject.py
# app.py
from flask import Flask
from flask_restful import Api
from routes import MyObject

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

api.add_resource(MyObject, '/')

if __name__ == '__main__':
    app.run()
# __init__.py
from myobject import MyObject
# myobject.py
from flask_restful import Resource


class MyObject(Resource):
    def get(self):
        return {'hello': 'world'}

When I run my application (python app.py), I get a ModuleNotFoundError: No module named 'myobject'
I don’t understand why python can’t find my module myobject. Is there something i’m missing in my __init__.py

Asked By: Portevent

||

Answers:

For __init__.py, it also needs the relative import or absolute import path in order to work correctly.

# __init__.py

# relative import
from .myobject import MyObject

# absolute import
from routes.myobject import MyObject

In another approach, you can write to import MyObject more specifically like this and leave __init__.py an empty file.

# app.py
# ...

from routes.myobject import MyObject

# ...
Answered By: Fony Lew

I believe the problem is due to your app running in the "main" directory and your import residing in a sub directory. Basically your app thinks you are trying to import "/main/myobject.py" instead of "/main/routes/myobject.py"

Change your import in __init__ to from .myobject import MyObject

The . means "this directory" (essentially).

Answered By: OneMadGypsy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.