I would really appreciate if someone could take a look at this code. I am not very advanced, so ANY kind of feedback and critique would be precious to me.
What this program is supposed to do is to go to a given URL, download the list of cities, for which it will download the data, based on a https://openweathermap.org/api . It should be run on a regular basis and write all of the results to the CSV file.
It is divided into two parts. The first one consists only of the scheduler, final function which is being run by it and the list of columns I want to get as the final result.
Code is written for Python 3.6.
from API.helpers import get_weather_data, json_to_df, create_dict
import schedule, time
URL = 'https://pm1aapplicantsdata.blob.core.windows.net/databases/CitiesWeather/CitiesWeather.csv'
columns = ["name","sys.country","main.temp",
"main.humidity","main.pressure",
"visibility", "wind.speed"]
#Writing results to CSV
def weather_api(URL):
dict = create_dict(URL)
for city, code in dict.items():
data = get_weather_data(city, code)
json_to_df(data, columns)
schedule.every().day.at("10:30").do(weather_api, URL)
while True:
schedule.run_pending()
time.sleep(1)
Here is the second part, which is my "helper" file.
import json
import requests
from pandas.io.json import json_normalize
import pandas as pd
import os
import requests
import csv
api_key = "xxxxxxxxxxxxxxxxxxxxxxx"
#function to build api requests
def build_request(city, code):
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = base_url + "appid=" + api_key + "&q=" + city +"," + code
return complete_url
#function to get weather data
def get_weather_data(city, code):
url = build_request(city, code)
try:
response = requests.get(url)
response.status_code
except requests.exceptions.HTTPError:
print('Error occured while downloading data')
except requests.exceptions.URLError:
print('Error occured while downloading data')
citydataJSON = response.text
citydata = json.loads(citydataJSON)
return citydata
def json_to_df(data, columns):
df = pd.DataFrame.from_dict(json_normalize(data), orient='columns')
new_df = df[columns]
new_df.insert(0, 'TimeStamp', pd.datetime.now().replace(microsecond=0))
if not os.path.isfile('weather.csv'):
return new_df.to_csv('weather.csv', header='column_names', index=False)
else:
return new_df.to_csv('weather.csv', mode='a', header=False, index=False)
#creating a dictionary of cities and city codes(based on the CSV file downloaded from a given URL
def create_dict(URL):
with requests.Session() as s:
dict = {}
download = s.get(URL)
decoded_content = download.content.decode('utf-8')
cs = csv.reader(decoded_content.splitlines(), delimiter=',')
next(cs, None)
my_list = list(cs)
for row in my_list:
dict[row[0]] = row[1]
return dict