12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- # -*- coding: utf-8 -*-
- """
- @Author : peng
- @Time : 2023-8-18 10:45:46
- @File :WeatherControl.py
- """
- import datetime
- from Ansjer.config import LOGGER
- import time
- from django.views import View
- 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):
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.GET, operation, request)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.POST, operation, request)
- def validation(self, request_dict, operation, request):
- lang = request_dict.get('lang', 'en')
- response = ResponseObject(lang)
- if operation == 'get': # 获取天气
- return self.get_weather(request_dict, response)
- else:
- return response.json(414)
- @staticmethod
- def get_weather(request_dict, response):
- """
- 获取天气
- @param request_dict: 请求参数
- @request_dict uid: 设备uid
- @param response: 响应对象
- @return: response
- """
- uid = request_dict.get('uid')
- if not uid:
- return response.json(444, 'uid')
- uid_set_qs = UidSetModel.objects.filter(uid=uid).values('tb_city_information_id')
- if not uid_set_qs.exists():
- return response.json(173)
- redis_obj = RedisObject()
- city_id = uid_set_qs[0]['tb_city_information_id']
- if city_id == 0:
- return response.json(10, '请更新设备影子地区信息')
- 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_hash_data('city_id_{}_weather'.format(city_id), time_stamp)
- if weather:
- temp, humidity = weather.split('/')
- else:
- city_obj = WeatherInfo(city_id)
- 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_hash_data('city_id_{}_weather'.format(city_id),
- {temp_time: '{}/{}'.format(item['temp'], item['humidity'])})
- redis_obj.set_expire('city_id_{}_weather'.format(city_id), 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)
|