diff --git a/src/my_package/get_data.py b/src/my_package/get_data.py new file mode 100644 index 0000000..ed83c3f --- /dev/null +++ b/src/my_package/get_data.py @@ -0,0 +1,72 @@ +# Import of needed libaries +import requests +import os +from dotenv import load_dotenv +import json +import matplotlib.pyplot as plt + +load_dotenv() + +# Gets the key, from my env file +API_KEY = os.getenv("API_KEY") + +# User input the city, for the weather +city_name = input("Enter a city in Norway: ") +country_code = "NO" + +# Temporarily standard times +start = 1742079600 +end = 1742166000 + +# Gets the data from the API - openweathermap.org +def get_data(): + # f-string url, to add the "custom" variables to the API-request + url = f"https://history.openweathermap.org/data/2.5/history/city?q={city_name},{country_code}&units=metric&type=hour&start={start}&end={end}&appid={API_KEY}" + + # Saves the API-request for the url + response = requests.get(url) + + # Checks if the status code is OK + if response.status_code == 200: + + # Converts the data into json + data = response.json() + + # Ensure the 'data' folder exists in the root of the project + os.makedirs('data', exist_ok=True) # Creates 'data' folder if it doesn't exist + + # Write the JSON data to a file inside the 'data' folder + file_path = os.path.join('data', 'data.json') # Creates 'data/data.json' + + # Opens and write the data to a json file + with open(file_path, 'w') as json_file: + json.dump(data, json_file, indent=4) + + # Prints when succed + print(f"Data has been written to {file_path}") + + return data + else: + # If html status code != 200, print the status code + print("Failed to fetch data from API. Status code:", response.status_code) + +# Stores the data in the myData variable +myData = get_data() + +# Empty dict for temperature +temperature = {} + +# Iterates through myData dict, and add the dt (unix_time) and temp to temperature dict +if "list" in myData: + for item in myData["list"]: + if "main" in item and "temp" in item["main"]: + temperature[item["dt"]] = (item["main"]["temp"]) + +# print(temperature) + +# A test plot, to get a visual look of the data +x_temp = temperature.keys() +y_temp = temperature.values() + +plt.plot(x_temp, y_temp) +plt.show()