def decode_response(data): try: temp = data.get('main', {}).get('temp', '') humidity = data.get('main', {}).get('humidity', '') city_id = data.get('id') w = Weather(city_id=city_id, temp=temp, humidity=humidity, ts=str(datetime.now())) except Exception as ex: print(ex) w = Weather(city_id='', temp=0.0, humidity=0.0, ts=str(datetime.now())) return w
def weather_get(self, location: str, on: datetime) -> Optional[Weather]: with self.engine.connect() as connection: results = connection.execute( """ select * from weathers where location = %s and DATE(`on`) = DATE(%s) """, (location, on.isoformat())) for result in results: return Weather(id=result['id'], location=result['location'], temperature=float(result['temperature']), phrase=result['phrase'], on=result['on']) return None
def gen_data(year, month, day): for i in range(0, 24): temp_0_6 = randrange(9, 15) temp_6_12 = randrange(14, 18) temp_12_18 = randrange(18, 24) temp_18_24 = randrange(16, 20) hum_0_6 = randrange(50, 70) hum_6_12 = randrange(50, 60) hum_12_18 = randrange(37, 52) hum_18_24 = randrange(40, 52) if (i <= 6): w = Weather(date=datetime.datetime(int(year), int(month), int(day), i, 0, 0), humidity=hum_0_6, temperature=temp_0_6) elif (i <= 12): w = Weather(date=datetime.datetime(int(year), int(month), int(day), i, 0, 0), humidity=hum_6_12, temperature=temp_6_12) elif (i <= 18): w = Weather(date=datetime.datetime(int(year), int(month), int(day), i, 0, 0), humidity=hum_12_18, temperature=temp_12_18) elif (i <= 24): w = Weather(date=datetime.datetime(int(year), int(month), int(day), i, 0, 0), humidity=hum_18_24, temperature=temp_18_24) db.session.add(w) db.session.commit() return Response(status=200)
def response_data(response: Response): weather = Weather() if response.status_code != 200: return weather data = response.json() weather.city = data['name'] temp = data['main']['temp'] weather.temperature = temp + (1 if temp % int(temp) else 0) weather.description = data['weather'][0]['description'] weather.currently = data['weather'][0]['main'] weather.date = data['dt'] return weather
def update(self): d = datetime.today() if d.minute != 0: d1 = d.replace(minute=0, second=0) + timedelta(hours=1) time_to_wait = (d1 - d).total_seconds() print(time_to_wait) time.sleep(time_to_wait) while True: h, t = DHT11.take_temp_and_humidity() w = Weather(humidity=h, temperature=t, date=datetime.today()) db.session.add(w) db.session.commit() time.sleep(PAUSE_PERIOD * 60) print(t) if self.stopped: return
def convertJsonToWeather(self, data): weather = Weather() for key, value in data.json().items(): if ObjectUtil.existField(key, 'coord'): if ObjectUtil.existField(value, 'lat'): weather.setCoordLat(value['lat']) if ObjectUtil.existField(value, 'lon'): weather.setCoordLon(value['lon']) if ObjectUtil.existField(key, 'main'): if ObjectUtil.existField(value, 'temp'): weather.setTemp(value['temp']) if ObjectUtil.existField(value, 'feels_like'): weather.setFeelsLike(value['feels_like']) if ObjectUtil.existField(value, 'temp_max'): weather.setTempMax(value['temp_max']) if ObjectUtil.existField(value, 'temp_min'): weather.setTempMin(value['temp_min']) if ObjectUtil.existField(value, 'pressure'): weather.setPressure(value['pressure']) if ObjectUtil.existField(value, 'humidity'): weather.setHumidity(value['humidity']) if 'sea_level' in value: weather.setSeaLevel(value['sea_level']) if 'grnd_level' in value: weather.setGrndLevel(value['grnd_level']) if ObjectUtil.existField(key, 'visibility'): weather.setVisibility(value) if ObjectUtil.existField(key, 'wind'): if ObjectUtil.existField(value, 'speed'): weather.setWindSpeed(value['speed']) if ObjectUtil.existField(value, 'deg'): weather.setWindDeg(value['deg']) if ObjectUtil.existField(value, 'gust'): weather.setWindGust(value['gust']) if ObjectUtil.existField(key, 'clouds'): weather.setCloudsAll(value['all']) if ObjectUtil.existField(key, 'dt'): weather.setDt(datetime.utcfromtimestamp(value)) if ObjectUtil.existField(key, 'sys'): if ObjectUtil.existField(value, 'country'): weather.setCountry(value['country']) if ObjectUtil.existField(value, 'sunrise'): weather.setSunrise(datetime.utcfromtimestamp(value['sunrise'])) if ObjectUtil.existField(value, 'sunset'): weather.setSunset(datetime.utcfromtimestamp(value['sunset'])) if ObjectUtil.existField(key, 'timeszone'): weather.setTimezone(value) if ObjectUtil.existField(key, 'name'): weather.setCity(value) return weather
def test_model_weather(self): # create w = Weather() w.ip = '1.1.1.1' w.country = 'country' w.flag = 'flag' w.town = 'town' w.tendency = 'sunny' w.wind_speed = '0' w.temperature_min = '20' w.temperature_max = '25' w.temperature = '23' w.humidity = '50%' w.clouds = 'none' db.session.add(w) db.session.commit() self.assertTrue(w.id > 0, 'id must be defined, but it is not.') # search by IP ww = Weather.query.filter_by(ip='1.1.1.1').first() self.assertIsNotNone(ww, 'we did not find the test weather') # compare results self.assertEqual(w.ip, ww.ip, 'ip is not identical but it should be') self.assertEqual(w.country, ww.country, 'country is not identical but it should be') self.assertEqual(w.flag, ww.flag, 'flag is not identical but it should be') self.assertEqual(w.town, ww.town, 'town is not identical but it should be') self.assertEqual(w.tendency, ww.tendency, 'tendency is not identical but it should be') self.assertEqual(w.wind_speed, ww.wind_speed, 'wind speed is not identical but it should be') self.assertEqual(w.temperature_min, ww.temperature_min, 'temperature min is not identical but it should be') self.assertEqual(w.temperature_max, ww.temperature_max, 'temperature max is not identical but it should be') self.assertEqual(w.temperature, ww.temperature, 'temperature is not identical but it should be') self.assertEqual(w.humidity, ww.humidity, 'humidity is not identical but it should be') self.assertEqual(w.clouds, ww.clouds, 'clouds is not identical but it should be') # search unknown IP w2 = Weather.query.filter_by(ip='2.2.2.2').first() self.assertIsNone(w2, 'we did find a weather row for an unknown IP') # delete wd = Weather.query.get(w.id) self.assertEqual(wd.ip, '1.1.1.1', 'cannot retrieve test weather') db.session.delete(wd) db.session.commit() f = Weather.query.get(w.id) self.assertIsNone(f, 'test weather was not deleted')
def weather(): with open('tests/demo_dark_sky_data.json') as file_object: contents = json.load(file_object) return Weather.instantiate_weather(contents)
async def test_insert_db(): w = Weather(uid='123', city_id='aaa', temp=1.0, humidity=2.0, ts='12:00:00') res = await database.insert(w) assert res > 0
def update_weather(): if not request.json or 'ip' not in request.json: abort(400) # okay, we have the IP of the customer, so now we need to call a geo location service to retrieve the details headers = { 'x-rapidapi-host': "ip1.p.rapidapi.com", 'x-rapidapi-key': Config.X_RAPID_API_KEY } url = "https://ip1.p.rapidapi.com/" + request.json['ip'] try: response = requests.request("GET", url, headers=headers) response.raise_for_status() country = response.json()['country'] town = response.json()['city'] flag = response.json()['flag']['svg'] country_code = response.json()['country_code'] postal_code = response.json()['postal'] latitude = str(response.json()['latitude']) longitude = str(response.json()['longitude']) headers = { 'x-rapidapi-host': "community-open-weather-map.p.rapidapi.com", 'x-rapidapi-key': Config.X_RAPID_API_KEY } url = "https://community-open-weather-map.p.rapidapi.com/forecast" querystring = { 'q': '{},{}'.format(town, country_code), 'units': 'metric', 'lat': latitude, 'lon': longitude, 'lang': "en", 'cnt': "1", 'zip': postal_code } response = requests.request("GET", url, headers=headers, params=querystring) resp = response.json()['list'][0] response.raise_for_status() temperature_min = resp['main']['temp_min'] temperature_max = resp['main']['temp_max'] temperature = resp['main']['temp'] humidity = resp['main']['humidity'] tendency = resp['weather'][0]['description'] clouds = resp['weather'][0]['main'] wind_speed = resp['wind']['speed'] w = Weather.query.filter_by(ip=request.json['ip']).first() if not w: w = Weather() w.ip = request.json['ip'] w.country = country w.flag = flag w.town = town w.tendency = tendency w.wind_speed = wind_speed w.temperature_min = temperature_min w.temperature_max = temperature_max w.temperature = temperature w.humidity = humidity w.clouds = clouds db.session.add(w) else: setattr(w, 'country', country) setattr(w, 'flag', flag) setattr(w, 'town', town) setattr(w, 'tendency', tendency) setattr(w, 'wind_speed', wind_speed) setattr(w, 'temperature', temperature) setattr(w, 'temperature_min', temperature_min) setattr(w, 'temperature_max', temperature_max) setattr(w, 'humidity', humidity) setattr(w, 'clouds', clouds) db.session.commit() return jsonify({'ip': request.json['ip']}), 201 except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other error occurred: {err}') abort(400)