Django No Module Named With Inner Package Using - python

I want to write my own python package inside django's app. It looks like that: I have secondary app. It totally works except one thing. Someday I'd decided to make my app more structured. And there where problems started. First of all, I've added python package(with simple init.py inside directory) to the app. Then I've added second package inside that package. And when I try to run django.setup() inside packages' files, I'm getting this error: ModuleNotFoundError: No module named '<primary settings container module name goes here>'
How to make my custom package's functions working properly?

The problem is that settings module isn't "viewable" from your package, e.g. you should add the location of main directory to PATH variable, which could be done like this:
from sys import path
from pathlib import Path
path.append(str(Path(__file__).resolve().parent))
Or you can simply add it permanently to system PATH.

Related

import module in Django

I have a project with structure like on this picture.
Folders structure
Where 'backend' folder is Django project folder.
I need to import module from another folder 'main' inside Django app file, i.e. import main.Text_Generator in backend.app.views file.
I tried: from ...main.Text_Generator import *. This raise an error while running a server: "attempted relative import beyond top-level package"
And from main.Text_Generator import *, also error "No module named 'main'"
What is the correct way to do such import?
Add this:
import sys
sys.path.append("..")
And then you should be able to get it with:
from main.Text_Generator import *
You're using a module outside your Django project. I would recommend moving the folder inside your project directory [or app directory] rather than messing with your PATH. If you move main inside backend your existing stuff will work.

Easiest way to import the modules from parent folder?

I have my folder setup as such.
Desktop/project1/
Inside project1, I have the main.py where I have all my functions stored, as well as a folder for each instance. So it looks like this.
Desktop/project1/main.py
Desktop/project1/user1/
Desktop/project1/user2/
and inside the user folders, i have:
Desktop/project1/user1/user1.py
Desktop/project1/user2/user2.py
I need to be able to import and use the functions from main.py in each user.py folder inside the folder for that user. Any Idea how to do this easily?
I am using Pycharm, and when I start typing this in, it auto fills it for me, like it can see both the main.py, as well as the functions inside it, but then when I run the program I get an error.
from main import function1
ModuleNotFoundError: No module named 'main'
Thanks
You can just add the directory's path to your sys.path using
import sys
sys.path.append(r'path\to\dir')
After that you can normally import the file.
You can retrieve the parent directory's path using pathlib.
Try to create an empty file __init__.py in your module directory. __init__ can detect your custom python modules

Python: Import scrypt from subfolder to another subfolder

I am working on some python project (2.7) and I have issue with imports. When I run main.py it start scripts from tests folder etc. and save output to logs and everything works fine.
/root------------
-logs
-staticCfg
-config.py
-tests
-systemTest
-scrypt1.py
-scrypt2.py
-userTest
-uScrypt1.py
main.py
My static variables (email, name etc.) are located in config.py. I need to import config.py in scrypt1.py or scrypt2.py. I tryed adding __init__.py to tests, systemTest and staticCfg folder but I always get an error.
In my scrypt1.py:
import staticCfg as cfg
...
or
from staticCfg import *
...
I get the error:
ImportError: No module named staticCfg
The import mechanism of Python can be a bit tricky.
You can refer to the documentation for more information: Python Import Mechanism
When you use absolute imports (your import does not start with a .) as you do, the import path will start from your main script (the one you launch). In your case, it's scrypt1.py. So starting from this location, python can't find the package staticCfg.
For me, the simplest solution is to create a main script in your root directory and call scrypt1.py from there (imported using from tests.systemTet import scrypt1.py). In this case, the base package will be your root folder and you will have access to the package staticCfg from all your script files as you wanted to do.
you may add root folder to PYTHONPATH.

Can't import modules - ImportError: No module named

I've created a new app called engineapp. Inside this app, there is a folder engine which is a Scrapy project.
When I try to import model from storage app inside top.py file, it returns:
from storage.models import TopItem
ImportError: No module named storage.models
Or the similar problem, when I try to import settings of scrapy project:
from engineapp.engine.engine import settings
It returns:
from engineapp.engine.engine import settings
ImportError: No module named engineapp.engine.engine
This is when I run scrapy project from command line.
Both imports created PyCharm itself.
As you can see, I've added __init__() everywhere so python would be able to recognize those files.
Do you know what should I do to be able to import those files?
PyCharm autocomplete relies on different IDE settings. You've marked your realstate_scanner as sources root, so PyCharm can resolve imports for this. From docs:
These roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports.
If you can't import some module in python, you should check PATH/PYTHONPATH variables first to make sure python interpreter knows where to find your module.

Implementing Home Grown Plugins for a Python Service

I am writing a simple scheduling service. I don't want to hard-code all of the tasks it can schedule and instead would like to support plugins that can be dropped in a folder and loaded dynamically at runtime.
My plan is to have a JSON file (or any configuration file) that maps a task name to the location of a Python file (a module) which will have a class called Plugin. Pretty simple I thought. When someone schedules a task to run, they pass the task name and the time to run it. When the time elapses, the plugin is loaded (or reloaded) and is ran with any additional arguments passed to the scheduler.
I have been looking at the imp module to see how to load modules at runtime. I am not sure whether I want to list plugins using their physical location (file system path) or to use their module names like you'd see in a import statement. It seems imp wants to use physical location.
I got two different versions of this code "working". Here is one that uses importlib:
pluginName = self.__pluginLookup[pluginName]
module = import_module(pluginName)
module = reload(module) # force reload
plugin = module.Plugin()
return plugin
This is one I wrote using imp:
path = self.__pluginLookup[pluginName]
path, moduleName = split(path)
moduleName, extension = splitext(moduleName)
file, path, description = find_module(moduleName, [path])
with file:
module = load_module(moduleName, file, path, description)
plugin = module.Plugin()
return plugin
The problem I am running into is handling dependencies. If I have a plugin.py file that depends on a dependency.py file in the same folder, saying import dependency doesn't seem to work. Instead, it looks up the dependency from the PYTHONPATH.
How can I make the imports relative to the plugins themselves?
You could append path to sys.path:
import sys
sys.path.append(path)
where path is the directory containing the dependency.py.
If you have a plugins directory with an __init__.py, you can add that directory to sys.path. Then modules inside there can do from . import dependency to import another plugin. Or, if the plugin is itself a subpackage (i.e., a directory with its own __init__.py) then it can do from . import dep to import a dependency within the same plugin, or from .. import dep to import a dependency from the global plugins directory. With this setup you don't even need to use imp or the like; you can use the __import__ function, which works by module name.
One possible wrinkle, though, is you say the plugins directory will be "under the current working directory". What does that mean exactly? You mean you want people to be able to add plugins anywhere on the drive and still use them? It would be better to have one central plugins directory for your app, and add that to sys.path, and tell people to put their plugins there.

Categories