[英]How to import one module to another in Django/Python?
I'm just getting started with Python and Django. 我刚刚开始使用Python和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.
所以在我的Django应用程序中,我创建了一个新模块,在其中,我想导入父模块中定义的一些变量。 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
我试图导入constants.py
。
kafka_producer.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
. 但是,我
no module found error
。 What is the correct way of importing modules in Python? 在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. 通过这种方式,您将离开
kafka
目录,并且您位于my_app
目录中。
Can you please paste full trace of error, as in : ModuleNotFoundError: No module named --name 你可以粘贴完整的错误跟踪,如: ModuleNotFoundError:没有名为--name的模块
I want to know what it is saying in --name. 我想知道--name中的内容。
One thing you can try is adding path of your app to the environment variable PATH. 您可以尝试的一件事是将应用程序的路径添加到环境变量PATH。
Try adding below lines in your kafka_producer.py 尝试在kafka_producer.py中添加以下行
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath('__file__'))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.