Exemplo n.º 1
0
def dataWeatherHandler():
    weather = pywapi.get_weather_from_yahoo('MXJO0043', 'metric')
    message = "Weather report in " + weather['location']['city']
    message = message + ", Temperature " + weather['condition']['temp'] + " C"
    message = message + ", Atmospheric Pressure " + weather['atmosphere'][
        'pressure'] + " mbar"
    print message
Exemplo n.º 2
0
 def __init__(self):
     self.result = pywapi.get_weather_from_yahoo('SPXX0050', 'metric')
     icon = self.__code_to_something(self.result['condition']['code'])
     if icon:
         self.result['condition']['icon'] = icon
     if 'link' in self.result:
         self.result['condition']['link'] = self.result['link']
Exemplo n.º 3
0
 def post(self):
     invalid = False
     username = self.request.cookies.get("username")
     users = User.query(User.username == username).fetch()
     user = users[0]
     zip_code = str(self.request.get("zip"))
     user.zipcode = zip_code
     user.put()
     if self.postalValidate(zip_code):
         yahoo_result = pywapi.get_weather_from_yahoo(zip_code)
         currentTemp = ((float(yahoo_result['condition']['temp'])*1.8) + 32)
         conditions = str(yahoo_result['condition']['text'])
         location = str(yahoo_result['condition']['title'])
         location = location.replace("Conditions for ", "")
         template_values = {
             'currentTemp': currentTemp,
             'conditions': conditions,
             'location': location,
             'zip_code': zip_code,
             'user': user,
         }
         template = JINJA_ENVIRONMENT.get_template('weather.html')
         self.response.write(template.render(template_values))
     else:
         invalid = True
         template_values = {
             'invalid': invalid,
             'zip_code': zip_code
         }
         template = JINJA_ENVIRONMENT.get_template('weather.html')
         self.response.write(template.render(template_values))
Exemplo n.º 4
0
    def run(self, wcd, wci):
        """
        Displaying expected temperature
        """
        # Get current forecast
        if self.weather_service == "yahoo":
            current_weather_forecast = pywapi.get_weather_from_yahoo(self.location_id)
        elif self.weather_service == "weather_dot_com":
            current_weather_forecast = pywapi.get_weather_from_weather_com(self.location_id)
        else:
            print("Warning: No valid weather_forecast found!")
            return
        outdoor_temp = current_weather_forecast["current_conditions"]["temperature"]
        if self.temp_sensor_registered:
            try:
                indoor_temp = str(int(round(am2302_ths.get_temperature(4))))
                wcd.showText(outdoor_temp + "*", count=1, fps=8)
                wcd.showText(indoor_temp + "*", count=1, fg_color=wcc.GREEN, fps=8)
                wcd.showText(outdoor_temp + "*", count=1, fps=8)
                wcd.showText(indoor_temp + "*", count=1, fg_color=wcc.GREEN, fps=8)
            except:
                print("  Failed to read temperature sensor!")
                wcd.showText(outdoor_temp + "*   " + outdoor_temp + "*   " + outdoor_temp + "*", count=1, fps=8)
        else:
            wcd.showText(outdoor_temp + "*   " + outdoor_temp + "*   " + outdoor_temp + "*", count=1, fps=8)

        time.sleep(1)
Exemplo n.º 5
0
def show_temp():
    yahoo_weather = pywapi.get_weather_from_yahoo('78728', 'imperial')
    for ch in yahoo_weather['condition']['temp']:
        display.display_char_fade(ch, color_tools.random_rgb(), 300)
    display.display_char_fade(chr(0xb0), color_tools.random_rgb(), 300)
    display.display_char_fade('f', color_tools.random_rgb(), 300)
    time.sleep(0.4)
Exemplo n.º 6
0
    def Weather(self):
        for i in self.trying:
            i.Destroy()
            
        self.trying = []
        sizer = wx.GridBagSizer()
        temp_actuel=T.time()
        weather_com_result = pywapi.get_weather_from_weather_com('10001')
        yahoo_result = pywapi.get_weather_from_yahoo('10001')
        noaa_result = pywapi.get_weather_from_noaa('KJFK')
        weather1 = self.trying.append(wx.StaticText(self.BoxStock,-1,str("Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " +
         yahoo_result['condition']['temp'] + " C now "),pos=(50,50)))
       # labelStock = wx.StaticText(self.BoxStock,-1,label=weather1,pos=(30,30))
        #self.text.SetLabel(str(labelStock))
        #weather2 = "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + " C now "
        #labelStock = wx.StaticText(self.BoxStock,label=weather2,pos=(30,80))
        #self.text.SetLabel(str(labelStock))

        wx.CallLater(10000,self.Weather)
        message=string.lower(yahoo_result['condition']['text'])
        if message=="fair":
            #from PIL import Image
            #bidule = Image.open("image/nuage-noir-avec-de-la-pluie.jpg")
            #bidule.show()
            
            app= Application(redirect=True)
            app.MainLoop()
Exemplo n.º 7
0
def get_wind(zip, units):
    weather = pywapi.get_weather_from_yahoo(zip)
    wind = 'No wind'
    if weather['wind']['speed'] > 1:
        wind = 'Wind %dmph from %s' % (float(weather['wind']['speed']), \
               get_wind_direction(weather['wind']['direction']))
    return wind
Exemplo n.º 8
0
def show_temp():
    yahoo_weather = pywapi.get_weather_from_yahoo('78728', 'imperial')
    for ch in yahoo_weather['condition']['temp']:
        display.display_char_fade(ch, color_tools.random_rgb(), 300)
    display.display_char_fade(chr(0xb0), color_tools.random_rgb(), 300)
    display.display_char_fade('f', color_tools.random_rgb(), 300)
    time.sleep(0.4)
Exemplo n.º 9
0
  def GenerateWeatherConditionsText(self):
    zipcode = '89129'
    weather = pywapi.get_weather_from_yahoo(zipcode)
    condition  = weather['condition']['text'].encode('UTF-8')
    humidity = weather['atmosphere']['humidity'].encode('UTF-8')
    temp_celsius = float(weather['condition']['temp'])
    temp = str( round(self.celsius2farenheight(temp_celsius),2)).encode('UTF-8')
    wind_mps = float( weather['wind']['speed'] )
    wind = str( round(self.mps2mph(wind_mps),2) ).encode('UTF-8')

    date_1 = weather['forecasts'][0]['date']
    date_2 = weather['forecasts'][1]['date']
    time_1 = time.strftime("%a, %b %d",time.strptime(date_1, "%d %b %Y")).encode('UTF-8')
    time_2 = time.strftime("%a, %b %d",time.strptime(date_2, "%d %b %Y")).encode('UTF-8')
    forecast_temp_low_1 = str(int(self.celsius2farenheight(float(weather['forecasts'][0]['low'])))).encode('UTF-8')
    forecast_temp_high_1 = str(int(self.celsius2farenheight(float(weather['forecasts'][0]['high'])))).encode('UTF-8')
    forecast_text_1 = weather['forecasts'][0]['text'].encode('UTF-8')
    forecast_temp_low_2 = str(int(self.celsius2farenheight(float(weather['forecasts'][1]['low'])))).encode('UTF-8')
    forecast_temp_high_2 = str(int(self.celsius2farenheight(float(weather['forecasts'][1]['high'])))).encode('UTF-8')
    forecast_text_2 = weather['forecasts'][1]['text'].encode('UTF-8')

    text = '{pause=5}{typesetOff}{fastest}{amber}{5x5}{moverightin}{moverightout}today: {7x6}{green}' + condition.encode('UTF-8') +'{nl}'
    text = text + '{5x5}{amber}{moveleftin}{moveleftout}Temp: {red}{7x6}' + temp + ' degrees{nl}'
    text = text + '{5x5}{amber}{moverightin}{moverightout}Humidity: {green}{7x6}' + humidity + '%{nl}'
    text = text + '{5x5}{amber}{moveleftin}{moveleftout}Wind: {red}{7x6}' + wind + 'mph{nl}'
    text = text + '{newframe}{fastest}{amber}{7x6}{moveupin}{movedownout}Forecast:{nl}'
    text = text + '{green}' + time_1 + '{nl}'
    text = text + '{red}Low:' + forecast_temp_low_1 + ' High: ' +forecast_temp_high_1 + '{nl}'
    text = text + '{amber}' + forecast_text_1 + '{nl}'
    text = text + '{newframe}{fastest}{amber}{7x6}{movedownin}{moveupout}Forecast:{nl}'
    text = text + '{green}' + time_2 + '{nl}'
    text = text + '{red}Low:' + forecast_temp_low_2 + ' High: ' +forecast_temp_high_2 + '{nl}'
    text = text + '{amber}' + forecast_text_2 + '{nl}'
    return text
Exemplo n.º 10
0
def getWeatherMemoized():
	global lastweather, wTemp, wIcon
	#update hourly
	if (time.time() - lastweather > 60 * 60):
		lastweather = time.time()
		wres = pywapi.get_weather_from_yahoo('10001')
		wTemp = (wres['condition']['temp'] + u"°C"
			#+ wres['condition']['text']
		)

		#print wres

		cond = wres['condition']['text']
		if cond == u"Sunny":
			wIcon = u"⛭"
		elif cond == u"Mostly Sunny":
			wIcon = u"⛯"
		elif cond == u"Fair":
			wIcon = u"⚙"
		elif cond == u"Partly Cloudy":
			wIcon = u"⛅"
		elif cond == u"Cloudy":
			wIcon = u"☁"
		elif cond == u"Raining":
			wIcon = u"☔" #☂
		elif cond == u"Snowing":
			wIcon = u"⛄"
		else:
			wIcon = u"☭"
Exemplo n.º 11
0
    def Weather(self):
        for i in self.trying:
            i.Destroy()

        self.trying = []
        sizer = wx.GridBagSizer()
        temp_actuel = T.time()
        weather_com_result = pywapi.get_weather_from_weather_com('10001')
        yahoo_result = pywapi.get_weather_from_yahoo('10001')
        noaa_result = pywapi.get_weather_from_noaa('KJFK')
        weather1 = self.trying.append(
            wx.StaticText(
                self.BoxStock,
                -1,
                str("Yahoo says: It is " +
                    string.lower(yahoo_result['condition']['text']) + " and " +
                    yahoo_result['condition']['temp'] + " C now "),
                pos=(50, 50)))
        # labelStock = wx.StaticText(self.BoxStock,-1,label=weather1,pos=(30,30))
        #self.text.SetLabel(str(labelStock))
        #weather2 = "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + " C now "
        #labelStock = wx.StaticText(self.BoxStock,label=weather2,pos=(30,80))
        #self.text.SetLabel(str(labelStock))

        wx.CallLater(10000, self.Weather)
        message = string.lower(yahoo_result['condition']['text'])
        if message == "fair":
            #from PIL import Image
            #bidule = Image.open("image/nuage-noir-avec-de-la-pluie.jpg")
            #bidule.show()

            app = Application(redirect=True)
            app.MainLoop()
Exemplo n.º 12
0
def get_weather_info(location):
    id = get_location_id(location)
    result = pywapi.get_weather_from_yahoo(id, 'metric')
    if not result:
        return {}
    output = dict(result)
    return output
Exemplo n.º 13
0
    def get_todays_weather(self, weather_service):
        """
        Says today's weather forecast with the selected weather service
        :author Robert Zeni:
        :name get_todays_weather:
        :param weather_service - the service to use for weather retrieval
        :date March 19, 2017
        :return: void
        """
        if weather_service == WeatherServices.OpenWeatherMap.value:
            return "Weather retrieval using open weather map is not implemented yet."

        if weather_service == WeatherServices.Yahoo.value:
            yahoo_result = pywapi.get_weather_from_yahoo('10001')
            return "It is " + yahoo_result['condition'][
                'text'] + " and " + yahoo_result['condition'][
                    'temp'] + "degrees celsius now in New York.\n\n"

        if weather_service == WeatherServices.Weather_com.value:
            weather_com_result = pywapi.get_weather_from_weather_com('10001')
            return "Weather.com says: It is " + weather_com_result[
                'current_conditions']['text'] + " and " + weather_com_result[
                    'current_conditions'][
                        'temperature'] + "degrees celsius  now in New York.\n\n"

        if weather_service == WeatherServices.NOAA.value:
            noaa_result = pywapi.get_weather_from_noaa('KJFK')
            return "NOAA says it is, " + noaa_result[
                'weather'] + " and " + noaa_result[
                    'temp_c'] + "degrees celsius right now.\n"
Exemplo n.º 14
0
def get_weather_info(location):
    id = get_location_id(location)
    result = pywapi.get_weather_from_yahoo(id, 'metric')
    if not result:
        return {}
    output = dict(result)
    return output
Exemplo n.º 15
0
    def get(self):
        auth = tweepy.OAuthHandler('wJynZvsXCJDbxFavJZMuvQ','Ua9HSGqJntKpBMfTYuldjuplo3XUlC3QovTn7EOQ')
        auth.set_access_token('400026591-XCtPsJABBP5MGF13Q4xFVXZurRcVtCcJ0VaU9Dr5', '635W0s9PIVYxlVktp0hWiNkBfNS4ntuW7c2thGsp8')
        api = tweepy.API(auth)
		
	location = 'Mataram'
	f = urllib2.urlopen('http://api.wunderground.com/api/da229b2203c824d3/geolookup/conditions/q/IA/' + location +'.json')
	json_string = f.read()
	parsed_json = json.loads(json_string)
	
	resYahoo = pywapi.get_weather_from_yahoo('IDXX0032', 'metric')
	
	time = datetime.datetime.utcnow() + datetime.timedelta(hours = 8)
	location = parsed_json['location']['city']
	current = parsed_json['current_observation']['weather']
	temp_c = parsed_json['current_observation']['temp_c']
	humidity = parsed_json['current_observation']['relative_humidity']
	visibility = parsed_json['current_observation']['visibility_km']
	f.close()
	
	sunrise = resYahoo['astronomy']['sunrise']
	sunset = resYahoo['astronomy']['sunset']
	wind = resYahoo['wind']['speed'] + ' km'
	winddir = resYahoo['wind']['direction'] 
	
	update = time.strftime("%Y-%m-%d, %H:%M") + ' WITA : ' + location + ' ' + current + ' ' + str(temp_c) +' C' + ', Humidity: ' + humidity  +', ' + ' Visibility: ' + visibility + ' km'
	update = update + ', Wind: ' + wind  + ', Sunrise: ' + sunrise + ', Sunset: ' + sunset
	self.response.out.write(update)
	api.update_status(update)
Exemplo n.º 16
0
        def run(self):
		old_temp = 0
		old_humidity = 0
		old_dewpoint = 0
                while (True):

			try:
				yahooweather_result = pywapi.get_weather_from_yahoo(readID)
				if yahooweather_result != "":
					condizioni = yahooweather_result['condition']['text']
					temperatura = float(yahooweather_result['condition']['temp'])
					umidita = float(yahooweather_result['atmosphere']['humidity'])
					dew = calc_dewpoint(temperatura, umidita)
					if temperatura != old_temp:
						if (readTempUnits == 'f' or readTempUnits == 'F'):
							tempF = round(celsius_to_fahrenheit(temperatura))
							client.emit_event(temp, "event.environment.temperaturechanged", tempF, "F")
						else:
       			                 		client.emit_event(temp, "event.environment.temperaturechanged", temperatura, "C")
					if umidita != old_humidity:
		       				client.emit_event(humidity, "event.environment.humiditychanged", umidita, "%")
		                        search_Rain = string.find(condizioni, "Rain")
					search_Drizzle = string.find(condizioni, "Drizzle")
		                        if (search_Rain >= 0) or (search_Drizzle >=0):
						client.emit_event(rain,"event.device.statechanged", "255", "")

		                        else :
						client.emit_event(rain,"event.device.statechanged", "0", "")

			except KeyError:
				print "Error retrieving weather data!"
			old_temp = temperatura
			old_humidity = umidita
			old_dewpoint = dew
			time.sleep (readWaitTime)
Exemplo n.º 17
0
def weather(args):
    

    try:
        result = pywapi.get_weather_from_yahoo(
            str(args[0]).replace("_", " "), "imperial")
        current_conditions = result["condition"][
            "title"] + ": " + result["condition"]["text"] + \
            ", " + result["condition"]["temp"]
        five_day_forecast = result["forecasts"]
        forecast_1 = str(five_day_forecast[0]["day"]) + ": " + str(five_day_forecast[0]["text"]) + ", " + str(
            five_day_forecast[0]["high"]) + ", " + str(five_day_forecast[0]["low"]) + " | "
        forecast_2 = str(five_day_forecast[1]["day"]) + ": " + str(five_day_forecast[1]["text"]) + ", " + str(
            five_day_forecast[1]["high"]) + ", " + str(five_day_forecast[1]["low"]) + " | "
        forecast_3 = str(five_day_forecast[2]["day"]) + ": " + str(five_day_forecast[2]["text"]) + ", " + str(
            five_day_forecast[2]["high"]) + ", " + str(five_day_forecast[2]["low"]) + " | "
        forecast_4 = str(five_day_forecast[3]["day"]) + ": " + str(five_day_forecast[3]["text"]) + ", " + str(
            five_day_forecast[3]["high"]) + ", " + str(five_day_forecast[3]["low"]) + " | "
        forecast_5 = str(five_day_forecast[4]["day"]) + ": " + str(five_day_forecast[4][
            "text"]) + ", " + str(five_day_forecast[4]["high"]) + ", " + str(five_day_forecast[4]["low"])
        forecasts = forecast_1 + forecast_2 + \
            forecast_3 + forecast_4 + forecast_5

        return current_conditions # + " | Forecasts: " + forecasts
    except:
        return "Zip codes only, at the moment, plz."
Exemplo n.º 18
0
    def weather_info(self):
        details = pywapi.get_weather_from_yahoo(CITY_ID)

        if 'error' in details:
            logging.critical('City not found. Shutting down weather thread.')
            sys.exit()
        
        weather_data = {'{0}'  : details['location']['city'],
                        '{1}'  : details['condition']['date'],
                        '{2}'  : details['condition']['code'],
                        '{3}'  : details['condition']['temp'],
                        '{4}'  : details['condition']['text'],
                        '{5}'  : details['astronomy']['sunrise'],
                        '{6}'  : details['astronomy']['sunset'],
                        '{7}'  : details['atmosphere']['humidity'],
                        '{8}'  : details['atmosphere']['pressure'],
                        '{9}'  : details['forecasts'][0]['day'],
                        '{10}' : details['forecasts'][0]['text'],
                        '{11}' : details['forecasts'][0]['code'],
                        '{12}' : details['forecasts'][0]['low'],
                        '{13}' : details['forecasts'][0]['high'],
                        '{14}' : details['forecasts'][1]['day'],
                        '{15}' : details['forecasts'][1]['text'],
                        '{16}' : details['forecasts'][1]['code'],
                        '{17}' : details['forecasts'][1]['low'],
                        '{18}' : details['forecasts'][1]['high']}

        outstring = insert_data(self.format_string, weather_data)

        with open(os.path.expanduser('~/.local/share/skutter/weather'), 'w') as g:
            g.write(outstring)
Exemplo n.º 19
0
def weather(args):

    try:
        result = pywapi.get_weather_from_yahoo(
            str(args[0]).replace("_", " "), "imperial")
        current_conditions = result["condition"][
            "title"] + ": " + result["condition"]["text"] + \
            ", " + result["condition"]["temp"]
        five_day_forecast = result["forecasts"]
        forecast_1 = str(five_day_forecast[0]["day"]) + ": " + str(
            five_day_forecast[0]["text"]) + ", " + str(
                five_day_forecast[0]["high"]) + ", " + str(
                    five_day_forecast[0]["low"]) + " | "
        forecast_2 = str(five_day_forecast[1]["day"]) + ": " + str(
            five_day_forecast[1]["text"]) + ", " + str(
                five_day_forecast[1]["high"]) + ", " + str(
                    five_day_forecast[1]["low"]) + " | "
        forecast_3 = str(five_day_forecast[2]["day"]) + ": " + str(
            five_day_forecast[2]["text"]) + ", " + str(
                five_day_forecast[2]["high"]) + ", " + str(
                    five_day_forecast[2]["low"]) + " | "
        forecast_4 = str(five_day_forecast[3]["day"]) + ": " + str(
            five_day_forecast[3]["text"]) + ", " + str(
                five_day_forecast[3]["high"]) + ", " + str(
                    five_day_forecast[3]["low"]) + " | "
        forecast_5 = str(five_day_forecast[4]["day"]) + ": " + str(
            five_day_forecast[4]["text"]) + ", " + str(
                five_day_forecast[4]["high"]) + ", " + str(
                    five_day_forecast[4]["low"])
        forecasts = forecast_1 + forecast_2 + \
            forecast_3 + forecast_4 + forecast_5

        return current_conditions  # + " | Forecasts: " + forecasts
    except:
        return "Zip codes only, at the moment, plz."
Exemplo n.º 20
0
    def run(self, wcd, wci):
        """
        Displaying expected temperature
        """
        # Get current forecast
        if self.weather_service == 'yahoo':
            current_weather_forecast = pywapi.get_weather_from_yahoo(self.location_id)
        elif self.weather_service == 'weather_dot_com':
            current_weather_forecast = pywapi.get_weather_from_weather_com(self.location_id)
        else:
            print('Warning: No valid weather_forecast found!')
            return
        outdoor_temp = current_weather_forecast['current_conditions']['temperature']
        if self.temp_sensor_registered:
            try:
                indoor_temp = str(int(round(am2302_ths.get_temperature(self.pin_temp_sensor))))
                wcd.showText(outdoor_temp + '*', count=1, fps=8)
                wcd.showText(indoor_temp + '*', count=1, fg_color=wcc.GREEN, fps=8)
                wcd.showText(outdoor_temp + '*', count=1, fps=8)
                wcd.showText(indoor_temp + '*', count=1, fg_color=wcc.GREEN, fps=8)
            except:
                print('  Failed to read temperature sensor!')
                wcd.showText(outdoor_temp + '*   ' + outdoor_temp + '*   ' + outdoor_temp + '*', count=1, fps=8)
        else:
            wcd.showText(outdoor_temp + '*   ' + outdoor_temp + '*   ' + outdoor_temp + '*', count=1, fps=8)

        if wci.waitForExit(1.0):
            return
Exemplo n.º 21
0
def checkOutdoorTemp(zip_code):
    """Gets outdoor temperature for our ZIP code from Yahoo!"""
    try:
        yahoo_com_result = pywapi.get_weather_from_yahoo( zip_code, units = 'metric' )
        outdoor_temperature = int(yahoo_com_result['condition']['temp'])
    except (KeyError, AttributeError, httplib.BadStatusLine):
        outdoor_temperature = 0
    return outdoor_temperature
Exemplo n.º 22
0
def weather(request):
    locations = ["94041", "90008", "97202", "94110", "10024", 
                 "02111", "60605", "23454", "32804", "75204", 
                 "98112", ]
    forecasts = []
    for location in random.sample(locations, 4):
        forecasts.append(pywapi.get_weather_from_yahoo(location))
    return render_to_response("petclinic/weather/weather_basic.html", { 'forecasts': forecasts })
Exemplo n.º 23
0
def forecast():
  yahoo_result = pywapi.get_weather_from_yahoo(weather_code)
  del yahoo_result['forecasts'][0]
  text = ""
  for forecast in yahoo_result['forecasts']:
    text += "%s: %s %sC | " % (forecast['day'],string.lower(forecast['text']),forecast['high'])

  return text
Exemplo n.º 24
0
    def get_yahoo_weather(location):

        if not pywapi:
            return None

        weather_data = WeatherData()
        weather_data.parse_yahoo_data(pywapi.get_weather_from_yahoo(str(location), units='imperial'))
        return weather_data
Exemplo n.º 25
0
    def processCmd(self, oMsg):
        city = 'Quebec'
        country = 'CA'
        location = city + ', ' + country
        yahoo_result = pywapi.get_weather_from_yahoo('CAXX0385')

        result = "It is " + string.lower(yahoo_result['condition']['text']) + \
            " and " + yahoo_result['condition']['temp'] + "C now in " + location + "."
        return result
Exemplo n.º 26
0
	def setWeather(self):
		''' get weather from yahoo.com for Torun: PLXX0028 '''
		print "Retrieving Yahoo's weather..."
		result = pywapi.get_weather_from_yahoo('PLXX0028', 'metric')

		(self.tempHistory, historyStr) = self.setHistory(self.tempHistory, result['condition']['temp'], Data.TEMP_HISTORY_LENGTH)
		self.writeHistory('tempHistory', self.tempHistory)

		return ('<LI>Forecast for Torun. Day: %s - %s. Preassure: %s. Condition: %s. Temp: <b>%s</b>. %s' %(result['astronomy']['sunrise'], result['astronomy']['sunset'], result['atmosphere']['pressure'], result['condition']['text'], result['condition']['temp'], historyStr))
Exemplo n.º 27
0
def getWeatherInfo(zipcode):
    weatherList = []
    result = pywapi.get_weather_from_yahoo(zipcode)
    weatherList = [float(result['condition']['temp']), 
                   float(result['atmosphere']['humidity']), 
                   float(result['wind']['speed'])
                  ]

    return weatherList
Exemplo n.º 28
0
 def load_temp(this, zipcode):
     yahoo = pywapi.get_weather_from_yahoo(str(zipcode))
     yd=json.dumps(yahoo)
     temp=yahoo["condition"]["temp"]    
     pressure=yahoo["atmosphere"]["pressure"]
     windspeed=yahoo["wind"]["speed"]
     direction=yahoo["wind"]["direction"]
     humidity=yahoo["atmosphere"]["humidity"]
     this.save_wx(zipcode,temp,humidity,pressure,windspeed,direction)
Exemplo n.º 29
0
def getWeather():
	result = pywapi.get_weather_from_yahoo('FRXX1567', 'metric')
	string = result['html_description']
	string = string.replace("\n", "")
	# On enleve le surplus et la pub ;-)
	string = string.replace("(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)<br/>", "")
	string = string.replace("<br /><a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Cachan__FR/*http://weather.yahoo.com/forecast/FRXX1567_c.html\">Full Forecast at Yahoo! Weather</a><BR/><BR/>", "")
    
	return string
Exemplo n.º 30
0
    def processCmd(self, oMsg):
        city = 'Quebec'
        country = 'CA'
        location = city + ', ' + country
        yahoo_result = pywapi.get_weather_from_yahoo('CAXX0385')

        result = "It is " + string.lower(yahoo_result['condition']['text']) + \
            " and " + yahoo_result['condition']['temp'] + "C now in " + location + "."
        return result
Exemplo n.º 31
0
def weather(request):
    locations = ["94041", "90008", "97202", "94110", "10024",
                 "02111", "60605", "23454", "32804", "75204",
                 "98112", "84102", "97219", "84043", "12345"]
    forecasts = []
    for location in locations:
        forecasts.append(pywapi.get_weather_from_yahoo(location))

    return render(request, 'weather/weather.html', {'forecasts': forecasts})
Exemplo n.º 32
0
    def getWeather():
        result = pywapi.get_weather_from_yahoo( str(ZIP), units = 'imperial' )
        string = result['html_description']
        string = string.replace("\n", "")

        #You will likely have to change these strings, unless you don't mind the additional garbage at the end.
        string = string.replace("(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)<br/>", "")
        string = string.replace("<br /><a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Nashville__TN/*http://weather.yahoo.com/forecast/USTN0357_f.html\">Full Forecast at Yahoo! Weather</a><BR/><BR/>", "")
        return string
def weather_listener(zip_code):
	print("called")
	while 1:
		msg = osc_message_builder.OscMessageBuilder(address = "/filter")
		yahoo_result = pywapi.get_weather_from_yahoo(zip_code)
		tempVal = round(int(yahoo_result['condition']['temp'])*9/5 + 32, 1)
		sendOSCMessage(tempVal, "/weather_sender")
		print (tempVal)
		sleep(60)
    def getWeather():
        result = pywapi.get_weather_from_yahoo( str(ZIP), units = 'imperial' )
        string = result['html_description']
        string = string.replace("\n", "")

        #You will likely have to change these strings, unless you don't mind the additional garbage at the end.
        string = string.replace("(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)<br/>", "")
        string = string.replace("<br /><a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Nashville__TN/*http://weather.yahoo.com/forecast/USTN0357_f.html\">Full Forecast at Yahoo! Weather</a><BR/><BR/>", "")
        return string
Exemplo n.º 35
0
    def run(self, wcd, wci):
        """
        Displaying expected temperature
        """
        # Get current forecast
        if self.weather_service == 'yahoo':
            current_weather_forecast = pywapi.get_weather_from_yahoo(
                self.location_id)
            outdoor_temp = current_weather_forecast['current_conditions'][
                'temperature']
        elif self.weather_service == 'weather_dot_com':
            current_weather_forecast = pywapi.get_weather_from_weather_com(
                self.location_id)
            outdoor_temp = current_weather_forecast['current_conditions'][
                'temperature']
        elif self.weather_service == 'meteoswiss':
            outdoor_temp = (json.loads(
                requests.get(
                    'https://www.meteoschweiz.admin.ch/product/output/weather-widget/forecast/version__20210514_1034/de/'
                    + zipcode + '00.json',
                    headers={
                        'referer':
                        'https://www.meteoschweiz.admin.ch/home/service-und-publikationen/produkte.html'
                    }).text))['data']['current']['temperature']
        else:
            logging.warning('No valid weather_forecast found!')
            return
        if self.temp_sensor_registered:
            try:
                indoor_temp = str(
                    int(round(am2302_ths.get_temperature(
                        self.pin_temp_sensor))))
                wcd.showText(outdoor_temp + '*', count=1, fps=8)
                wcd.showText(indoor_temp + '*',
                             count=1,
                             fg_color=wcc.GREEN,
                             fps=8)
                wcd.showText(outdoor_temp + '*', count=1, fps=8)
                wcd.showText(indoor_temp + '*',
                             count=1,
                             fg_color=wcc.GREEN,
                             fps=8)
            except:
                logging.error('Failed to read temperature sensor!')
                wcd.showText(outdoor_temp + '*   ' + outdoor_temp + '*   ' +
                             outdoor_temp + '*',
                             count=1,
                             fps=8)
        else:
            wcd.showText(outdoor_temp + '*   ' + outdoor_temp + '*   ' +
                         outdoor_temp + '*',
                         count=1,
                         fps=8)

        if wci.waitForExit(1.0):
            return
Exemplo n.º 36
0
def getWeatherInfo(zipcode):
    weatherList = []
    result = pywapi.get_weather_from_yahoo(zipcode)
    weatherList = [
        float(result['condition']['temp']),
        float(result['atmosphere']['humidity']),
        float(result['wind']['speed'])
    ]

    return weatherList
Exemplo n.º 37
0
def getForecast(city, day=0):
	result = pywapi.get_weather_from_yahoo(city, 'metric')
	forecast = result['forecasts'][day]
	
	day = forecast['day']
	high = forecast['high']
	low = forecast['low']
	text = forecast['text']

	return [day, high, low, text]
Exemplo n.º 38
0
def usrInput():
    global weather
    global displayTempIn
    import pywapi, pprint, string, time
    location = raw_input("Which ZIP code would you like to know the weather for? \n")
    displayTempIn = raw_input("Would you like the Temperature to be displayed in Celsius or Fahrenheit? \n")
    p = pprint.PrettyPrinter(indent=4)
    weather = pywapi.get_weather_from_yahoo(location)
    displayTempIn=displayTempIn.lower() #converts to lower case to prevent any errors from occuring
    return weather;
Exemplo n.º 39
0
def weather(request):
    locations = [
        "94041", "90008", "97202", "94110", "10024", "02111", "60605", "23454",
        "32804", "75204", "98112", "84102", "97219", "84043", "12345"
    ]
    forecasts = []
    for location in locations:
        forecasts.append(pywapi.get_weather_from_yahoo(location))

    return render(request, 'weather/weather.html', {'forecasts': forecasts})
Exemplo n.º 40
0
def getWeatherInfo(zipcode):
    weatherList = []
    windList = []
    yahooResult = pywapi.get_weather_from_yahoo(zipcode)
    #WindList[Chill, Direction, Speed]
    windList = [int(yahooResult['wind']['chill']), int(yahooResult['wind']['direction']), float(yahooResult['wind']['speed'])] 
    #weatherList[temperature, Humidity, windList];
    weatherList = [int(yahooResult['condition']['temp']), int(yahooResult['atmosphere']['humidity']), windList ]
    #print weatherList
    return weatherList
Exemplo n.º 41
0
 def get_weather(self, id):
     #self.yahoo_result = pywapi.get_weather_from_yahoo(id, 'en')
     self.yahoo_result = pywapi.get_weather_from_yahoo(id, self.locale_name)#'CHXX0008'  2151330         10001   USNY0996
     self.get_temperature_unit()
     self.get_code()
     #fp = open("/tmp/yahoo1.txt", "w")
     #print >> fp, "--------------"
     #print >> fp, self.yahoo_result
     #fp.close()
     self.sessionDaemon.access_weather('yahoo', 'kobe')
Exemplo n.º 42
0
    def retrieveYAHOOWeatherJson(self, cityCodes):
        # stores the values of the jsons for each city
        cityData = []

        # loop through city codes and save the json data
        for key, value in cityCodes.iteritems():
            cityData.append(pywapi.get_weather_from_yahoo(value))

        # save the json list to the classes list of jsons
        self.listOfCityData = cityData
Exemplo n.º 43
0
def getWeather(request):
    try:
        # Zip Code
        location_id = '02139'
        forecast = pywapi.get_weather_from_yahoo(location_id, '')

        tmp_condition = forecast['condition']
        current = {
            'temp': tmp_condition['temp'],
            'description': tmp_condition['text'],
            'icon': code2image(tmp_condition['code']),
        }

        tmp_today = forecast['forecasts'][0]
        today = {
            'high': tmp_today['high'],
            'low': tmp_today['low'],
            'description': tmp_today['text'],
            'icon': code2image(tmp_today['code']),
        }

        tmp_tomorrow = forecast['forecasts'][1]
        tomorrow = {
            'high': tmp_tomorrow['high'],
            'low': tmp_tomorrow['low'],
            'description': tmp_tomorrow['text'],
            'icon': code2image(tmp_tomorrow['code']),
        }

    except:
        current = {
            'temp': 'NA',
            'description': 'NA',
            'icon': 'NA',
        }

        today = tomorrow = {
            'high': 'NA',
            'low': 'NA',
            'description': 'NA',
            'icon': 'NA',
        }

    weather = {
        'title': 'Yahoo! Weather',
        'current': current,
        'today': today,
        'tomorrow': tomorrow,
    }

    jsonout = json.dumps(weather)
    return HttpResponse(jsonout, content_type="application/json")
Exemplo n.º 44
0
 def run(self):
     try:
         weather = pywapi.get_weather_from_yahoo(self.location(),
                                                 self.units)
         if 'error' not in weather:
             self._current = weather
             self.changed.emit(self)
         else:
             self.error.emit(weather['error'])
     except:
         self.error.emit('Could not retrieve weather.')
     self._t = threading.Timer(30, self.run)
     self._t.start()
Exemplo n.º 45
0
 def run(self, wcd, wci):
     '''
     Displaying expected temperature
     '''
     # Get current forecast
     if self.weather_service == 'yahoo':
         current_weather_forecast = pywapi.get_weather_from_yahoo(self.location_id)
     elif self.weather_service == 'weather_dot_com':
         current_weather_forecast = pywapi.get_weather_from_weather_com(self.location_id)
     else:
         print('Warning: No valid weather_forecast found!')
         return
     wcd.showText(current_weather_forecast['current_conditions']['temperature'] + '*', count=1)
     time.sleep(0.6)
Exemplo n.º 46
0
def usrInput():
    global weather
    global displayTempIn
    import pywapi, pprint, string, time
    location = raw_input(
        "Which ZIP code would you like to know the weather for? \n")
    displayTempIn = raw_input(
        "Would you like the Temperature to be displayed in Celsius or Fahrenheit? \n"
    )
    p = pprint.PrettyPrinter(indent=4)
    weather = pywapi.get_weather_from_yahoo(location)
    displayTempIn = displayTempIn.lower(
    )  #converts to lower case to prevent any errors from occuring
    return weather
Exemplo n.º 47
0
    def GenerateWeatherConditionsText(self):
        zipcode = '89129'
        weather = pywapi.get_weather_from_yahoo(zipcode)
        condition = weather['condition']['text'].encode('UTF-8')
        humidity = weather['atmosphere']['humidity'].encode('UTF-8')
        temp_celsius = float(weather['condition']['temp'])
        temp = str(round(self.celsius2farenheight(temp_celsius),
                         2)).encode('UTF-8')
        wind_mps = float(weather['wind']['speed'])
        wind = str(round(self.mps2mph(wind_mps), 2)).encode('UTF-8')

        date_1 = weather['forecasts'][0]['date']
        date_2 = weather['forecasts'][1]['date']
        time_1 = time.strftime("%a, %b %d",
                               time.strptime(date_1,
                                             "%d %b %Y")).encode('UTF-8')
        time_2 = time.strftime("%a, %b %d",
                               time.strptime(date_2,
                                             "%d %b %Y")).encode('UTF-8')
        forecast_temp_low_1 = str(
            int(self.celsius2farenheight(float(
                weather['forecasts'][0]['low'])))).encode('UTF-8')
        forecast_temp_high_1 = str(
            int(
                self.celsius2farenheight(float(
                    weather['forecasts'][0]['high'])))).encode('UTF-8')
        forecast_text_1 = weather['forecasts'][0]['text'].encode('UTF-8')
        forecast_temp_low_2 = str(
            int(self.celsius2farenheight(float(
                weather['forecasts'][1]['low'])))).encode('UTF-8')
        forecast_temp_high_2 = str(
            int(
                self.celsius2farenheight(float(
                    weather['forecasts'][1]['high'])))).encode('UTF-8')
        forecast_text_2 = weather['forecasts'][1]['text'].encode('UTF-8')

        text = '{pause=5}{typesetOff}{fastest}{amber}{5x5}{moverightin}{moverightout}today: {7x6}{green}' + condition.encode(
            'UTF-8') + '{nl}'
        text = text + '{5x5}{amber}{moveleftin}{moveleftout}Temp: {red}{7x6}' + temp + ' degrees{nl}'
        text = text + '{5x5}{amber}{moverightin}{moverightout}Humidity: {green}{7x6}' + humidity + '%{nl}'
        text = text + '{5x5}{amber}{moveleftin}{moveleftout}Wind: {red}{7x6}' + wind + 'mph{nl}'
        text = text + '{newframe}{fastest}{amber}{7x6}{moveupin}{movedownout}Forecast:{nl}'
        text = text + '{green}' + time_1 + '{nl}'
        text = text + '{red}Low:' + forecast_temp_low_1 + ' High: ' + forecast_temp_high_1 + '{nl}'
        text = text + '{amber}' + forecast_text_1 + '{nl}'
        text = text + '{newframe}{fastest}{amber}{7x6}{movedownin}{moveupout}Forecast:{nl}'
        text = text + '{green}' + time_2 + '{nl}'
        text = text + '{red}Low:' + forecast_temp_low_2 + ' High: ' + forecast_temp_high_2 + '{nl}'
        text = text + '{amber}' + forecast_text_2 + '{nl}'
        return text
Exemplo n.º 48
0
    def update_weather(self):
        try:
            locations = self.config.get_locations()
            weather = pywapi.get_weather_from_yahoo(locations[0])
            self.weather = CurrentWeather(weather)
            self.forecasts = filter(
                self.not_today, [Forecast(x) for x in weather['forecasts']])

            self.indicator.update_weather(self.weather)
        except Exception as e:
            print e
            self.weather = None

        return True
Exemplo n.º 49
0
def getWeatherInfoInCSV(zipcode, filename):
    wList = []
    result = pywapi.get_weather_from_yahoo(zipcode)
    wList = [
        result['condition']['title'], result['condition']['date'],
        int(result['condition']['temp']),
        float(result['atmosphere']['humidity']),
        int(result['wind']['chill']),
        int(result['wind']['direction']),
        float(result['wind']['speed'])
    ]
    fd = open('%s.csv' % filename, 'ab')
    writer = csv.writer(fd)
    writer.writerow((wList))
    fd.close()
    return wList
Exemplo n.º 50
0
def say_weather(cmdProcessor):
    """ 
        retrieve weather info from yahoo and say the current condition.
        requires pywapi to be installed 
    """
    import pywapi  # must be installed (sudo pip install pywapi)
    location_code = cmdProcessor.config.get("misc", "weather_location_code")
    logging.info("Getting weather from {0}".format(location_code))
    result = pywapi.get_weather_from_yahoo(location_code, "metric")
    strTemplate = "{location}. It's {condition} with temperature of {temperature} celsius. " \
                  "Sunrise at {sunrise} and sunset at {sunset}"
    whatToSay = strTemplate.format(location=result['condition']['title'],
                                   condition=result['condition']['text'],
                                   temperature=result['condition']['temp'],
                                   sunrise=result['astronomy']['sunrise'],
                                   sunset=result['astronomy']['sunset'])
    say_something(whatToSay)
Exemplo n.º 51
0
    def run(self, wcd, wci):
        """
        Displaying expected temperature
        """
        # Get current forecast
        if self.weather_service == 'yahoo':
            current_weather_forecast = pywapi.get_weather_from_yahoo(
                self.location_id)
        elif self.weather_service == 'weather_dot_com':
            current_weather_forecast = pywapi.get_weather_from_weather_com(
                self.location_id)
        else:
            logging.warning('No valid weather_forecast found!')
            return
        outdoor_temp = current_weather_forecast['current_conditions'][
            'temperature']
        if self.temp_sensor_registered:
            try:
                indoor_temp = str(
                    int(round(am2302_ths.get_temperature(
                        self.pin_temp_sensor))))
                wcd.showText(outdoor_temp + '*', count=1, fps=8)
                wcd.showText(indoor_temp + '*',
                             count=1,
                             fg_color=wcc.GREEN,
                             fps=8)
                wcd.showText(outdoor_temp + '*', count=1, fps=8)
                wcd.showText(indoor_temp + '*',
                             count=1,
                             fg_color=wcc.GREEN,
                             fps=8)
            except:
                logging.error('Failed to read temperature sensor!')
                wcd.showText(outdoor_temp + '*   ' + outdoor_temp + '*   ' +
                             outdoor_temp + '*',
                             count=1,
                             fps=8)
        else:
            wcd.showText(outdoor_temp + '*   ' + outdoor_temp + '*   ' +
                         outdoor_temp + '*',
                         count=1,
                         fps=8)

        if wci.waitForExit(1.0):
            return
Exemplo n.º 52
0
def find_weather(zipcode):
    weather = pywapi.get_weather_from_yahoo(zipcode)
    text = weather['condition']['text']
    temp = int(weather['condition']['temp'])
    if 'Snow' in text:
        return snowing, temp
    if 'Sunny' in text:
        return sunny, temp
    if 'Cloudy' in text:
        return cloudy, temp
    if 'Thunder' in text:
        return thundering, temp
    if 'Rain' in text:
        return raining, temp
    if 'Showers' in text:
        return raining, temp
    if 'Fair' in text:
        return fair, temp
Exemplo n.º 53
0
    def report(self):

        result = pywapi.get_weather_from_yahoo('MXJO0043', 'metric')

        message = "Reporte del Clima en " + result['location']['city']
        message = message + ", Temperatura " + result['condition'][
            'temp'] + " grados centigrados"
        message = message + ", Presion Atmosferica " + result['atmosphere'][
            'pressure'] + " milibares"
        message = message + ", Visibilidad " + result['atmosphere'][
            'visibility'] + " kilometros"
        message = message + ", Humedad " + result['atmosphere'][
            'humidity'] + " por ciento"
        message = message + ", El Sol se oculta a las " + result['astronomy'][
            'sunset']
        print message

        command = ['libraries/voicerss.sh', 'es-mx', message]
        proc = subprocess.call(command)
Exemplo n.º 54
0
def motionthread():
    global buffer1, occupied, hour, musicprocess, minute, alarmset
    while True:
        # Get comparison image
        buffer2 = captureTestImage()

        # Count changed pixels
        changedPixels = 0
        for x in xrange(0, 50):
            for y in xrange(0, 25):
                # Just check green channel as it's the highest quality channel
                pixdiff = abs(buffer1[x, y][1] - buffer2[x, y][1])
                if pixdiff > threshold:
                    changedPixels += 1

        # Take action if pixels changed
        if changedPixels > sensitivity:
            action()
        if datetime.datetime.now().hour == hour and datetime.datetime.now(
        ).minute == minute and alarmset == True:
            forecasttext = unicodedata.normalize(
                'NFKD',
                pywapi.get_weather_from_yahoo(
                    '84003',
                    '')['forecasts'][0]['text']).encode('ascii', 'ignore')
            engine = pyttsx.init()
            engine.say("The weather today is " + forecasttext)
            engine.runAndWait()
            music()
            occupied = True
        # Swap comparison buffers
        #image1 = image2
        buffer1 = buffer2
        if occupied == True:
            quit = False
        else:
            quit = True
        while not quit:
            musicprocess.wait()
            buffer2 = captureTestImage()
            buffer1 = buffer2
            occupied = False
            quit = True
Exemplo n.º 55
0
    def run(self, wcd, wci):
        '''
        Displaying expected temperature
        '''
        # Get current forecast
        if self.weather_service == 'yahoo':
            current_weather_forecast = pywapi.get_weather_from_yahoo(
                self.location_id)
        elif self.weather_service == 'weather_dot_com':
            current_weather_forecast = pywapi.get_weather_from_weather_com(
                self.location_id)
        else:
            print('Warning: No valid weather_forecast found!')
            return
        outdoor_temp = current_weather_forecast['current_conditions'][
            'temperature']
        if self.temp_sensor_registered:
            try:
                indoor_temp = str(int(round(am2302_ths.get_temperature(4))))
                wcd.showText(outdoor_temp + '*', count=1, fps=8)
                wcd.showText(indoor_temp + '*',
                             count=1,
                             fg_color=wcc.GREEN,
                             fps=8)
                wcd.showText(outdoor_temp + '*', count=1, fps=8)
                wcd.showText(indoor_temp + '*',
                             count=1,
                             fg_color=wcc.GREEN,
                             fps=8)
            except:
                print('  Failed to read temperature sensor!')
                wcd.showText(outdoor_temp + '*   ' + outdoor_temp + '*   ' +
                             outdoor_temp + '*',
                             count=1,
                             fps=8)
        else:
            wcd.showText(outdoor_temp + '*   ' + outdoor_temp + '*   ' +
                         outdoor_temp + '*',
                         count=1,
                         fps=8)

        time.sleep(1)
Exemplo n.º 56
0
def getWeather():
    yahoo_result = pywapi.get_weather_from_yahoo(
        ZipCode
    )  #Uses pywapi to fetch the weather from the Yahoo weather api (Found this to be the least spotty service)
    if yahoo_result == '':
        #DoNothing just leave the previous weather
        print "Weather Returned Nothing"
    else:
        print yahoo_result['condition']['text']
        weatherString = string.capitalize(
            yahoo_result['condition']['text']) + ", "
        temp_Celcius = yahoo_result['condition']['temp']

        if CelciusUnit == False:
            weatherString = weatherString + CelciusToFahrenheit(temp_Celcius)
        elif CelciusUnit == True:
            weatherString = weatherString + temp_Celcius

        print time.strftime("%H:%M:%S %a %m:%d:%Y %z") + weatherString
        return weatherString
def weather(city_name, city_code):
	 
	#city_code = unicode(city_code)
	#city_name = unicode(city_name)

	try:
		#weather_com_result = pywapi.get_weather_from_weather_com(city_code)
		weather_com_result = pywapi.get_weather_from_yahoo(city_code)

	except Exception as e:
		print("Exception : ", e)

	if not weather_com_result.__contains__('error'):
		weather_result = "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "degree celcius now in " + city_name

		tts(weather_result)

	else:
		tts_offline('It seems that there is a connecting problem, please check your internet connection')		
		print("It seems that there is a connecting problem, please check your internet connection")
Exemplo n.º 58
0
def command_forecast(bot, user, channel, args):
    """This module tells weather forecast for location"""
    if not has_pywapi:
        return

    result_dict = pywapi.get_weather_from_yahoo(args)
    if not all(result_dict.values()):
        bot.say(channel, 'unknown location')
        return

    def format_day(day):
        return (u'%s: %s (%.0f°C/%.0f°C)' % (day['day_of_week'],
                            day['condition'],
                            fahrenheit_to_celcius(day['low']),
                            fahrenheit_to_celcius(day['high'])))

    answerstr = u'%s: ' % (result_dict['forecast_information']['city'])
    answerstr += u", ".join(format_day(day) for day in result_dict['forecasts'])

    bot.say(channel, answerstr.encode('utf-8'))
Exemplo n.º 59
0
    def save(self, request, commit=True):
        if request.user.is_authenticated():
            user = request.user
            contexto = super(ContextForm, self).save(commit=False)
            yahoo_result = pywapi.get_weather_from_yahoo('BRXX3272')
            grad = yahoo_result['condition']['temp']
            contexto.weather = self.convert_grad_to_weather(grad)
            contexto.lat_position = self.cleaned_data["lat_position"]
            contexto.long_position = self.cleaned_data["long_position"]
            distance = self.cleaned_data["distance"]
            if commit:
                contexto.save()
                CurrentContext.objects.filter(user=user).update(current=False)
                CurrentContext.objects.create(user=user,
                                              context=contexto,
                                              distance_max=distance)
            ctx = {'form': form}
            return distance

        else:
            return HttpResponse(u"precisa está logado")