Python Forum

Full Version: Weather info using user api and city id
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello I hav ewritten below code to fetch weather info of given location but my program doesn't enter to main part.

from pandas import json
import urllib.request
import datetime

print("Note: Script needs User key and City code to display weather info\n"
      "Create your own User key in http://openweathermap.org/ \n"
      "Download City Code list from http://bulk.openweathermap.org/sample/city.list.json.gz\n")

def time_converter(time):
    converted_time = datetime.datetime.fromtimestamp(int(time)).strftime('%I:%M %p')
    return converted_time

def create_complete_url(User_key,City_code):
    base_url = 'http://api.openweathermap.org/data/2.5/weather?id='
    temp_unit = 'metric'#enter metric for degree or imperial for Fahrenheit
    complete_url = base_url+str(City_code)+'&mode=json&units='+temp_unit+'&APPID='+User_key
    return complete_url

def weather_data_from_url(complete_url):
    with urllib.request.urlopen(complete_url) as url:
        raw_weather_data = json.loads(url.read().decode('utf-8'))
    return raw_weather_data

def get_relevant_weather_data(raw_weather_data):
    my_weather_dict = {}  # To store retrieved weather data
    print(raw_weather_data)
    main = raw_weather_data.get('main')
    sys = raw_weather_data.get('sys')
    print("Loading weather  data to dictionary")
    my_weather_dict['City Name']=raw_weather_data.get('name')
    my_weather_dict['Country']=sys.get('country')
    my_weather_dict['Current Temperature']=main.get('temp')
    my_weather_dict['Temperature Min'] = main.get('temp_min')
    my_weather_dict['Temperature Max']=main.get('temp_max')
    my_weather_dict['Wind']=raw_weather_data.get('wind').get('speed')
    my_weather_dict['Wind Degree']=raw_weather_data.get('wind').get('deg')
    my_weather_dict['Humidity']=main.get('humidity')
    my_weather_dict['Cloudiness']=raw_weather_data.get('clouds').get('all')
    my_weather_dict['Pressure']=main.get('pressure')
    my_weather_dict['Sunrise at']=time_converter(sys.get('sunrise'))
    my_weather_dict['Sunset at']=time_converter(sys.get('sunset'))
    my_weather_dict['Sky']=raw_weather_data['weather'][0]['main']
    my_weather_dict['dt']=time_converter(raw_weather_data.get('dt'))
    return my_weather_dict

def display_my_weather_data(my_weather_data):
    print("I am inside display data function")
    temp_degree = '\xb0' + 'C'#for °C
    #temp_Fahrenheit = 'F'#for Fahrenheit
    print("Environmental parameters for the selected location:")
    print('Selected location is - {}, {}'.format(my_weather_data['City Name'], my_weather_data['Country']))
    current_temp_unit = str(my_weather_data['Current Temperature'])+ temp_degree
    print('Current Temperature: {}'.format(current_temp_unit))
    temp_min_unit = str(my_weather_data['Temperature Min'])+ temp_degree
    print('Temperature min: {}'.format(temp_min_unit))
    temp_max_unit = str(my_weather_data['Temperature Max'])+ temp_degree
    print('Temperature max: {}'.format(temp_max_unit))
    print('Wind Speed: {}, Degree: {}'.format(my_weather_data['Wind'], my_weather_data['Wind Degree']))
    print('Humidity: {}'.format(my_weather_data['Humidity']))
    print('Cloud: {}'.format(my_weather_data['Cloudiness']))
    print('Pressure: {}'.format(my_weather_data['Pressure']))
    print('Sunrise at: {}'.format(my_weather_data['Sunrise at']))
    print('Sunset at: {}'.format(my_weather_data['Sunset at']))
    print ('Sky: {}'.format(my_weather_data['Sky']))
    print('Last update from the server: {}'.format(my_weather_data['dt']))


if __name__ == '__main__':
    try:
        User_key = input("Enter user key")
        City_code =input("Enter city code")

        print("\nEntered User Key is ", User_key)
        print("Entered City Code is ", City_code)

        complete_url = create_complete_url(User_key,City_code)#create complete url
        raw_weather_data = weather_data_from_url(complete_url)#Get weather data from created url
        my_weather_data = get_relevant_weather_data(raw_weather_data)#extract relevant weather data from raw weather data
        print(my_weather_data)
        display_my_weather_data(my_weather_data)
    except IOError:
        print('no internet')
It stops at first print statement itself. it wll never come to User_key = input("Enter user key") this statment
Do you get any errors?
Output:
Note: Script needs User key and City code to display weather info Create your own User key in http://openweathermap.org/ Download City Code list from http://bulk.openweathermap.org/sample/city.list.json.gz
I got this output, after that it comes out of the programm there is no error. Im using python console.
(Jun-15-2018, 07:32 PM)Vimala Wrote: [ -> ]Im using python console.

save this script, e.g. myweather.py then run it from the command prompt. e.g c:\>python3 myweather.py
you may want to check this:

https://python-forum.io/Thread-Basic-How...ython-code
I run it in Jupyter (same as console, only much better Dance ) and it worked

First of all - remove try/except

Secondly - why do you use urllib Naughty when you could have done it with requests?
(Jun-15-2018, 07:48 PM)buran Wrote: [ -> ]
(Jun-15-2018, 07:32 PM)Vimala Wrote: [ -> ]Im using python console.
save this script, e.g. myweather.py then run it from the command prompt. e.g c:\>python3 myweather.py you may want to check this: https://python-forum.io/Thread-Basic-How...ython-code
I got below error
Error:
Traceback (most recent call last): File "E:\Python\MyProject\weather.py", line 1, in <module> from pandas import json File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\__init__.py", line 19, in <module> "Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy']
How did you install pandas? If it was through pip, dependencies should have been installed with it.
(Jun-15-2018, 08:01 PM)nilamo Wrote: [ -> ]How did you install pandas? If it was through pip, dependencies should have been installed with it.

I have installed Pandas via Pip and also installed dependencies
(Jun-15-2018, 07:59 PM)Vimala Wrote: [ -> ]
Error:
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\__init__.py", line 19, in <module> "Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy']
(Jun-15-2018, 08:08 PM)Vimala Wrote: [ -> ]I have installed Pandas via Pip and also installed dependencies
Apparently not. pip install numpy should help.
(Jun-15-2018, 07:59 PM)Vimala Wrote: [ -> ]
(Jun-15-2018, 07:48 PM)buran Wrote: [ -> ]save this script, e.g. myweather.py then run it from the command prompt. e.g c:\>python3 myweather.py you may want to check this: https://python-forum.io/Thread-Basic-How...ython-code
I got below error
Error:
Traceback (most recent call last): File "E:\Python\MyProject\weather.py", line 1, in <module> from pandas import json File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\__init__.py", line 19, in <module> "Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy']

And why do you import json from pandas - when there's the standard json module Wall ?