Search code examples
pythondjangofilepath

Import function from another file in same folder


I know this question has been asked many times in other posts, but I can't to solve it with the answers provided.

I am creating a Django app in which I have a .py file with some functions that I want to import in another file and use them. This is the code of the function to import (in 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

And this is the code where I want to import it, the file (service.py) is in the same folder and 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

When I run service.py I get this error:

File "service.py", line 4, in from .helpers import cargar_api ImportError: attempted relative import with no known parent package

I don't think it is an issue on how the paths are written in the import line because I'm letting VSCode to help me with that, is basically automatic.

Here is a screen on how the folders are structured:

enter image description here


Solution

  • Remove that . before helpers in service.py

    So it becomes :-

    from helpers import cargar_api