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?
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
I want to import a file from subdir and I get an error like that:
ModuleNotFoundError: No module named 'special'
│
├── constants.py
├── crawler.py
├── case.py ===================>>>> I working on this file
├── special
├── __init__.py
└── wantToImport.py =================>>>I want to import this file
My case.py like that:
from special.wantToImport import ImportClass
And my wantToImport.py file like that:
class ImportClass:
def mydefination(self):
#Some codes here
I want to use mydefinitioon function on my case.py file But I cannot import this file.
Why Im getting this error?
How can I solve this?
You should tell Python that your module's path is inside the current directory (using a .):
from .special.wantToImport import ImportClass
Try creating a __init__.py file in the directory where you are working and use it to refer your module.
│
root
├── constants.py
├── crawler.py
├── case.py ===================>>>> I working on this file
├── __init__.py
├── special
├── __init__.py
└── wantToImport.py =================>>>I want to import this file
inport it using
from root.special.wantToImport import ImportClass
I have a project
testci/
├── __init__.py
├── README.md
├── requirements.txt
├── src
│ ├── __init__.py
│ └── mylib.py
└── test
├── __init__.py
└── pow_test.py
When I run python3.6 test/pow_test.py I see an error:
File "test/pow_test.py", line 3, in
import testci.src.mylib as mylib
ModuleNotFoundError: No module named 'testci'
pow_test.py
from testci.src.mylib import get_abs
def test_abs():
assert get_abs(-10) == 10
How can I fix this error?
System details: Ububntu 16.04 LTS, Python 3.6.10
try this
from .src import mylib
from mylib import get_abs
if it won't work then import one by one. But don't import the root folder since the file you are importing to is on the same folder you are trying to import then it will always raise an error
Run Python with the -m argument within the base testsci package to execute as a submodule.
I made a similar mock folder structure:
├───abc_blah
│ │ abc_blah.py
│ │ __init__.py
│
└───def
│ def.py
│ __init__.py
abc_blah.py
print('abc')
def.py
import abc_blah.abc_blah
Execute like such:
python -m def.def
Correctly prints out 'abc' as expected here.
simply add __package__ = "testci" and also it is a good practice to add a try and except block
Your final code should look something like
try:
from testci.src.mylib import get_abs
except ModuleNotFoundError:
from ..testci.src.mylib import get_abs
for running it, type python -m test.pow_test
I think your issue is how the package is installed. The import looks fine to me. As it says CI I'm guessing you're having the package installed remotely with only the test folder somehow.
Try adding a setup.py file where you define that both the test as well as the src packages are part of your testci package.
there are many ways to organize a project, keep things consider in mind, structure should be simple and more scaleable, can differentiate the things in codebase easily.
one of the few good possible ways to structure a project is below
project/
├── app.py
├── dockerfile
├── pipfile
├── Readme.md
├── requiements.txt
├── src_code
│ ├── code
│ │ ├── __init__.py
│ │ └── mylib.py
│ └── test
│ ├── __init__.py
│ └── test_func.py
└── travisfile
here app.py is main file which is responsible to run your entire project
I am trying to run tests in radish, a Behaviour Driven Development environment for Python, but I am failing to do even the easiest of things.
I have this structure:
.
├── features
│ └── my.feature
└── radish
├── __init__.py
├── harness
│ ├── __init__.py
│ └── main.py
└── steps.py
When I do
python -c "import radish.harness"
from my working dir ".", things are fine.
When I do the same ("import radish.harness" or "import harness") in the file steps.py, I'm getting this when calling the command "radish features" from the same directory:
ModuleNotFoundError: No module named 'radish.harness'
or
ModuleNotFoundError: No module named 'harness'
The radish-bdd quick start guide quick start guide says about this:
How does radish find my python modules? radish imports all python
modules inside the basedir. Per default the basedir points to
$PWD/radish which in our case is perfectly fine.
Indeed a file placed in the radish directory will be imported automatically, but I am unable to import anything from within these files (apart from system libraries).
Can anyone advise me on how to import modules? I'm lost. It seems that my python knowledge on module import isn't helping.
I suggest you to move the 'harness' directory at the same level as 'features' and 'radish' directory.
.
├── features
│ └── my.feature
├── radish
│ ├── __init__.py
│ └── steps.py
└── harness
├── __init__.py
└── main.py
If you call radish from your working dir (".") like this:
radish -b radish features/my.feature
Then you can import your "harness" module from steps.py like this
import harness
That will work because in this case Python will find your "harness" module as it is in the current directory.
I'm building a Flask app with Python 3.5 following a tutorial, based on different import rules. By looking for similar questions, I managed to solve an ImportError based on importing from a nested folder by adding the folder to the path, but I keep failing at importing a function from a script in the same folder (already in the path). The folder structure is this:
DoubleDibz
├── app
│ ├── __init__.py
│ ├── api
│ │ ├── __init__.py
│ │ └── helloworld.py
│ ├── app.py
│ ├── common
│ │ ├── __init__.py
│ │ └── constants.py
│ ├── config.py
│ ├── extensions.py
│ ├── static
│ └── templates
└── run.py
In app.py I import a function from config.py by using this code:
import config as Config
but I get this error:
ImportError: No module named 'config'
I don't understand what's the problem, being the two files in the same folder.
Have you tried
import app.config as Config
It did the trick for me.
To import from the same folder you can do:
from .config import function_or_class_in_config_file
or to import the full config with the alias as you asked:
from ..app import config as Config
# imports all functions
import config
# you invoke it this way
config.my_function()
or
# import specific function
from config import my_function
# you invoke it this way
my_function()
If the app.py is invoked not from the same folder you can do this:
# csfp - current_script_folder_path
csfp = os.path.abspath(os.path.dirname(__file__))
if csfp not in sys.path:
sys.path.insert(0, csfp)
# import it and invoke it by one of the ways described above
Another, shorter way would be:
import .config as Config
I'm trying to create a basic blogging application in Python using Web.Py. I have started without a direcotry structure, but soon I needed one. So I created this structure:
Blog/
├── Application/
│ ├── App.py
│ └── __init__.py
|
├── Engine/
│ ├── Connection/
│ │ ├── __init__.py
│ │ └── MySQLConnection.py
│ ├── Errors.py
│ └── __init__.py
├── __init__.py
├── Models/
│ ├── BlogPostModel.py
│ └── __init__.py
├── start.py
└── Views/
├── Home.py
└── __init__.py
start.py imports Application.App, which contains Web.Py stuff and imports Blog.Models.BlogPostModel, which imports Blog.Engine.Connection.MySQLConnection.
Application.App also imports Engine.Errors and Views.Home. All these imports happen inside contructors, and all code inside all files are in classes. When I run python start.py, which contains these three lines of code:
from Application import App
app = App.AppInstance()
app.run()
The following stack trace is printed:
Blog $ python start.py
Traceback (most recent call last):
File "start.py", line 2, in <module>
Blog = App.AppInstance()
File "/home/goktug/code/Blog/Application/App.py", line 4, in __init__
from Blog.Views import Home
ImportError: No module named Blog.Views
But according to what I understand from some research, this should run, at least until it reaches something after App.py. Can anyone tell where I made the mistake? (I can provide more code on request, but for now I'm stopping here, as this one is getting messier and messier).
App.py contains the statement
from Blog.Views import Home
So Blog needs to be among the list of directories Python searches for modules (sys.path). That can be arranged in various ways.
Since you are starting the app with python start.py, the directory
containing start.py is automatically added to the search path. So
you could change
from Blog.Views import Home
to
from Views import Home
Another option would be to move start.py up one level, out of the
Blog directory. Then when you call python start.py, the
directory containing start.py will also be the directory
containing Blog. So Python would find Blog when executing from
Blog.Views ...
Finally, you could add the Blog directory to your PYTHONPATH environment
variable.
You can only import the module Blog if its parent directory (not Blog itself) is on python's path.
If you run your program from the Blog directory like you do, you can only imort Views directly, like you do with Application.App:
from Views import Home
instead of
from Blog.Views import Home
in your Application/App.py.