I am fairly new to python and need help taking a json file and incorporating it into the init in a class to be used through out, but I am getting the error below and don't understand why. I have a build a few classes before and this seems to look the same.
AttributeError: 'dict' object has no attribute 'zipcode'
I have a separate json file called config.json
that I have changed some information in (i.e. location and api key), but other than that, this is what I am working with.
config.json:
{
"unit_system":"metric",
"location_information":{
"country_code":"US",
"country_name":"United States",
"city":"New York City",
"state":"New York",
"postal":10001
},
"api_keys":{
"weather_api_key":"97a484e1039b7a0779b59f2e57e597a3"
}
}
weather.py
class weather:
"""weather retrieving app"""
def __init__(self, data):
"""initialize attributes for weather app"""
self.unit_system = data['unit_system']
#unit system
self.country_code = data['location_information']['country_code']
self.zipcode = data['location_information']['postal']
#location information
self.api_key = data['api_keys']['weather_api_key']
#api key informaation
def get_update(self):
threading.Timer(5.0, w.get_update).start()
#runs get_update every 5 seconds
#get weather information
weather_url = 'http://api.openweathermap.org/data/2.5/weather?zip=' \
+ str(self.zipcode) + ',' \
+ self.country_code + '&appid=' \
+ self.api_key
weather_request = requests.get(weather_url)
weather_data = weather_request.json()
temp_k = float(weather_data['main']['temp'])
#determine unit system conversions
if self.unit_system == 'english':
temp = (temp_k - 273.15) * 1.8 + 32
elif self.unit_system == 'metric':
temp = temp_k - 273.15
print(temp)
#return(temp)
import threading
import requests
import json
with open('config.json') as config_file:
config = json.load(config_file)
w = weather(config)
w.get_update()
weather
object by passing it adata
, likew = weather(config)
. Then you can callw.get_update()
. What you're doing is calling theweather.update
method and asking it to useconfig
as aweather
instance, which it isn't, so you get errors.