我知道这个问题在其他帖子中已经问过很多遍了,但是我无法通过提供的答案来解决。
我正在创建一个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时,出现以下错误:
来自.helpers的文件“ service.py”,第4行,导入cargar_api ImportError:尝试了相对导入,没有已知的父包
我不认为在导入行中如何编写路径是个问题,因为我让VSCode来帮助我基本上是自动的。
这是有关文件夹结构的屏幕:
.
在service.py中的帮助者之前将其删除
变成:-
from helpers import cargar_api
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句