Home > front end >  How to call a module inside a package in Python with Flask?
How to call a module inside a package in Python with Flask?

Time:10-18

CONTEXT. Python 3.9.1, Flask 2.0.1 and Windows 10

WHAT I WANT TO DO. Call a module located inside a custom package.

TROUBLE. No matter what I do, the console insists on telling me: ModuleNotFoundError: No module named 'my_package'

WHAT AM I DOING.

I am following the official Flask tutorial https://flask.palletsprojects.com/en/2.0.x/tutorial/index.html. Therefore, the structure of the project is basically this (with slight changes from the tutorial):

/flask-tutorial
├── flaskr/
│   ├── __init__.py
│   ├── db.py
│   ├── schema.sql
│   ├── templates/
│   ├── static/
│   └── my_package/
│       ├── __init__.py (this file is empty)
│       ├── auth.py
│       ├── backend.py
│       ├── blog.py
│       └── user.py
├── venv/
├── .env
├── .flaskenv
├── setup.py
└── MANIFEST.in

Inside the file /flask-tutorial/flaskr/init.py I try to call the modules that contain my blueprints:

from my_package import backend
from my_package import auth
from my_package import user
from my_package import blog

backend.bp.register_blueprint(auth.bp)
backend.bp.register_blueprint(user.bp)
backend.bp.register_blueprint(blog.bp)

app.register_blueprint(backend.bp)

When I running the application (with the flask run command), the console tells me ModuleNotFoundError: No module named 'my_package', indicating that the problem is in the line where it is from my_package import backend.

HOW I TRIED TO SOLVE THE PROBLEM (unsuccessfully).

First. I have created an empty file called init.py inside 'my_package'

Second. Inside the file /flask-tutorial/flaskr/init.py, before the problematic FROM, I have put:

import os.path
import sys
parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent)

On the internet there are several posts with this same problem. Many of them mention that the solution is to put a init.py file inside the package (I already did this and it does not work for me). Also, unfortunately the structure of the projects in question is different from mine.

Any ideas how to fix this?

CodePudding user response:

Change your code to

from .my_package import backend
from .my_package import auth
from .my_package import user
from .my_package import blog

backend.bp.register_blueprint(auth.bp)
backend.bp.register_blueprint(user.bp)
backend.bp.register_blueprint(blog.bp)

app.register_blueprint(backend.bp)

Just add a single dot . before the package name to import the package in the same parent package. In your case, __init__.py and my_package have a common flaskr as their parent package.

  • Related