How to import one module to another in Django/Python? - python

I'm just getting started with Python and Django. So within my Django application, I created a new module and within that, I want to import some variable defined in the parent module. However, I am getting certain errors while I tried various combinations.
Below is how my directory structure looks like
Now in my kafka_producer.py I am trying to import constants.py.
kafka_producer.py:
from confluent_kafka import Producer
import sys
import logging
import json
from my_app.constants import KAFKA_BROKER_URL
logging.basicConfig()
#Assign Configuration
conf = {'bootstrap.servers': KAFKA_BROKER_URL}
print(conf)
However, I am getting no module found error. What is the correct way of importing modules in Python?

It should work if you write:
from ..constants import KAFKA_BROKER_URL
Through this way, you leave the kafka directory and you are in your my_app directory.

Can you please paste full trace of error, as in :
ModuleNotFoundError: No module named --name
I want to know what it is saying in --name.
One thing you can try is adding path of your app to the environment variable PATH.
Try adding below lines in your kafka_producer.py
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath('__file__'))))

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.

I need help setting up my relative imports in python

I have spent so many hours trying out different answers on stack overflow that i no longer know what exactly is the proper way to use relative imports. Keep in mind this import should work on localhost and on a server
My project structure
init.py
Attempts to import Authenticate class in main.py result into ImportError: attempted relative import with no known parent package
Kindly give an explanation or links with working examples of importing in the same directory.
You are trying to import a Jupyter Notebook, not a class. This is why you get the ImportError.
Have a look at this: ipynb import another ipynb file
If you do not want to import from a Jupyter Notebook but from a module in a specified path you can try this:
import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()
You can also use relative import:
from foo import bar
Another option is to add a path to sys.path (over using import) to simplify things when importing more than one module from a single package:
import sys
# my_package dir contains mod_one.py, mod_two.py and mod_three.py
sys.path.append('/foo/bar/my_package')
from mod_one import foo
from mod_two import bar
from mod_three import foobar

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.

Importing from relative path in python syntax error

I am trying to import from relative path in my python program.
the class i would like to import is in
home/foo/bar/model.py
However, my current python script is in
home/best/user/test.py
i have tried to use
from ../../foo/bar import class
But it throws up a syntax error
When importing modules, python looks in the current working directory and in the paths in sys.path. You can add the directory of the script you would like to import to sys.path:
import sys
sys.path.append('home/foo/bar')
import model # imports home/foo/bar/model.py
You can't do that. You can't import from an explicitly specified path (without awful trickery). All Python imports are based on the systemwide import paths (in sys,path). You can't import anything that isn't reachable from sys,path (i.e., it's either on sys.path itself or it's inside a package that's on sys.path). The documenation has the details. If you want to be able to import from that file, you need to somehow add its directory (or the directory of its topmost containing package) to the path.

Python Import Module

Recently started a new Python project.
I am resolving a import module error where I am trying to import modules from the same directory.
I was following the solutions here but my situation is slightly different and as a result my script cannot run.
My project directory is as follows:
dir-parent
->dir-child-1
->dir-child-2
->dir-child-3
->__init__.py (to let python now that I can import modules from here)
->module1
->module2
->module3
->module4
->main.py
In my main.py script I am importing these module in the same directory as follows:
from dir-parent.module1 import class1
When I run the script using this method it throws a import error saying that there is no module named dir-parent.module1 (which is wrong because it exists).
I then change the import statement to:
from module1 import class1
and this seemed to resolve the error, however, the code I am working on has been in use for over 2.5 years and it has always imported modules via this method, plus in the code it refers to the dir-parent directory.
I was just wondering if there is something I am missing or need to do to resolve this without changing these import statements and legacy code?
EDIT: I am using PyCharm and am running off PyCharm
If you want to keep the code unchanged, I think you will have to add dir-parent to PYTHONPATH. For exemple, add the following on top of your main.py :
import os, sys
parent_dir = os.path.abspath(os.path.dirname(__file__)) # get parent_dir path
sys.path.append(parent_dir)
Python's import and pathing are a pain. This is what I do for modules that have a main. I don't know if pythonic at all.
# Add the parent directory to the path
CURRENTDIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if CURRENTDIR not in sys.path:
sys.path.append(CURRENTDIR)

Categories