【发布时间】:2021-01-16 04:55:26
【问题描述】:
我知道这个问题在其他帖子中被问过很多次,但我无法用提供的答案来解决它。
我正在创建一个 Django 应用程序,其中有一个 .py 文件,其中包含一些我想在另一个文件中导入并使用它们的功能。这是要导入的函数的代码(在 helpers.py 中):
from requests.exceptions import HTTPError
def cargar_api(url):
for url in [url]:
try:
response = requests.get(url)
response.raise_for_status()
except HTTPError as http_err:
print(f"Ocurrió un error HTTP: {http_err}")
except Exception as err:
print(f"Ocurrió otro error: {err}")
else:
print("API cargada")
data = response.json()
return data
这是我要导入的代码,文件(service.py)和helpers.py在同一个文件夹中:
import requests
from requests.exceptions import HTTPError
import os
from .helpers import cargar_api
WEATHER_API_KEY = os.environ.get("WEATHER_API_KEY")
# funcion que da todos los datos del clima segun las coordenadas
# adicionalmente agrega un key "recomendacion" para alertar al usuario de precauciones a tomar antes de salir
# informacion de cada dato de la API: https://www.weatherbit.io/api/weather-current
# diferentes opciones de descripciones y logos aqui: https://www.weatherbit.io/api/codes
def info_clima(latitud, longitud):
url_clima = f"https://api.weatherbit.io/v2.0/current?lat={latitud}&lon={longitud}&key={WEATHER_API_KEY}"
info_clima = cargar_api(url_clima)["data"][0]
descripcion_clima = info_clima["weather"]["description"]
if (
"Thunderstorm" in descripcion_clima
or "Drizzle" in descripcion_clima
or "Rain" in descripcion_clima
):
info_clima["recomendacion"] = "¡Sal con paraguas! Lloverá"
elif "snow" in descripcion_clima.lower():
info_clima["recomendacion"] = "Cuidado en la vía, nevará"
elif "Clear sky" in descripcion_clima:
info_clima["recomendacion"] = "El día estará despejado hoy, ¡protégete del sol!"
else:
info_clima["recomendacion"] = "¡Ten un excelente día!"
print(info_clima)
return info_clima
当我运行 service.py 时出现此错误:
文件“service.py”,第 4 行,在 from .helpers import cargar_api ImportError: 在没有已知父包的情况下尝试相对导入
我认为路径在导入行中的写入方式不是问题,因为我让 VSCode 来帮助我,基本上是自动的。
以下是有关文件夹结构的屏幕:
【问题讨论】:
-
将此作为评论,因为我不确定 100%,但如果它们与我要导入的脚本位于同一文件夹中,我不会在导入前使用句点。适用于我通常很简单的情况。
-
您应该将其发布为答案,因为它有效 XD,我盲目地依赖 VSC 来正确创建路径并且它不起作用。事实上 helpers 用警告强调,但它有效!
-
没关系,反正语法正确我也不确定。