SHARE
TWEET

Untitled

wpinda Dec 13th, 2016 77 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import requests
  2. import urllib.request
  3. import json
  4. import pymysql
  5. import pymysql.cursors
  6.  
  7. #Get data
  8.  
  9.  
  10. def GetAPIData(): #Get the dictionary from the API
  11.     fullsite = urllib.request.urlopen("http://api.openweathermap.org/data/2.5/weather?id=2759886&appid=4bde3f68e4ed269f928bd2535c2b30a0")
  12.     encoding = fullsite.info().get_content_charset('utf8')
  13.     data = json.loads(fullsite.read().decode(encoding))
  14.     return data
  15.  
  16.  
  17.  
  18. def GetToSave(): #Create the variable to save with SQL
  19.     data = GetAPIData()
  20.    
  21.     temperature = data.get('main').get('temp')
  22.     pressure = data.get('main').get('pressure')
  23.     humidity = data.get('main').get('humidity')
  24.     description = data.get('weather')[0].get('description')
  25.     wind_speed = data.get('wind').get('speed')
  26.     wind_degree = data.get('wind').get('deg')
  27.     print(type(temperature))
  28.  
  29.     sqldata = temperature, pressure, humidity, description, wind_speed, wind_degree
  30.  
  31.     return "INSERT INTO WEATHER VALUES(" + temperature + ")"
  32.  
  33.  
  34. def SaveToSQL(Data): #Save the data to the SQL server
  35.    
  36.     #connect to sql database
  37.     connection = pymysql.connect(host='localhost',
  38.                                  user='root',
  39.                                  password='Mysql',
  40.                                  db='test')                          
  41.     cursor = connection.cursor()
  42.                              
  43.     #save to sql database
  44.     try:
  45.         cursor.execute(to_save)
  46.         connection.commit()
  47.         print('IT WORKED')
  48.     except:
  49.         connection.rollback()
  50.         print('nope')
  51.  
  52.     #disconnect from server
  53.     connection.close()
  54.  
  55.  
  56.  
  57. SaveToSQL(GetToSave())
  58.  
  59. # testprint
  60. #print(type(description))
  61. #print(description)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top