Kaynağa Gözat

优化设备获取天气频率

peng 1 yıl önce
ebeveyn
işleme
7b3c9f41da
2 değiştirilmiş dosya ile 27 ekleme ve 5 silme
  1. 16 5
      Controller/WeatherControl.py
  2. 11 0
      Object/IPWeatherObject.py

+ 16 - 5
Controller/WeatherControl.py

@@ -4,6 +4,8 @@
 @Time : 2023-8-18 10:45:46
 @File :WeatherControl.py
 """
+import datetime
+
 from Ansjer.config import LOGGER
 import time
 
@@ -12,6 +14,7 @@ from Object.IPWeatherObject import WeatherInfo
 from Model.models import UidSetModel, CityInformation
 from Object.ResponseObject import ResponseObject
 from Object.RedisObject import RedisObject
+from Service.CommonService import CommonService
 
 
 class WeatherView(View):
@@ -50,19 +53,27 @@ class WeatherView(View):
             return response.json(173)
         redis_obj = RedisObject()
         city_id = uid_set_qs[0]['tb_city_information_id']
+        today = datetime.datetime.today()
+        now_time = datetime.datetime(today.year, today.month, today.day, today.hour)
+        time_stamp = CommonService.str_to_timestamp(now_time.strftime('%Y-%m-%d %H:%M:%S'))
+        temp, humidity = None, None
         try:
-            weather = redis_obj.get_data('city_id_{}_weather'.format(city_id))
+            weather = redis_obj.get_data('city_id_{}_{}_weather'.format(city_id, time_stamp))
             if weather:
                 temp, humidity = weather.split('/')
             else:
                 city_obj = WeatherInfo(city_id)
-                temp, humidity = city_obj.get_city_weather()
-                if temp and humidity:
-                    redis_obj.set_ex_data('city_id_{}_weather'.format(city_id), '{}/{}'.format(temp, humidity), 1800)
+                weather_list = city_obj.get_city_24_weather()
+                if weather_list:
+                    temp = weather_list[0]['temp']
+                    humidity = weather_list[0]['humidity']
+                    for item in weather_list:
+                        temp_time = CommonService.str_to_timestamp(item['date'] + ' ' + item['hour'] + ':00:00')
+                        redis_obj.set_ex_data('city_id_{}_{}_weather'.format(city_id, temp_time),
+                                              '{}/{}'.format(item['temp'], item['humidity']), 86400)
             if not all([temp, humidity]):
                 return response.json(10, '获取天气失败')
             return response.json(0, {'temp': temp, 'humidity': humidity})
         except Exception as e:
             print(e)
             return response.json(500)
-

+ 11 - 0
Object/IPWeatherObject.py

@@ -70,3 +70,14 @@ class WeatherInfo:
                 # 返回温湿度
                 return result['data']['condition']['temp'], result['data']['condition']['humidity']
         return None, None
+
+    def get_city_24_weather(self):
+        url = 'https://aliv18.data.moji.com/whapi/json/alicityweather/forecast24hours'  # 获取城市24小时天气
+        data = {'cityId': self.city_id}
+        response = requests.post(url, headers=self.headers, data=data, verify=False)
+        if response.status_code == 200:
+            result = response.json()
+            if result['code'] == 0:
+                # 返回天气列表
+                return result['data']['hourly']
+        return None