WeatherControl.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # -*- coding: utf-8 -*-
  2. """
  3. @Author : peng
  4. @Time : 2023-8-18 10:45:46
  5. @File :WeatherControl.py
  6. """
  7. from Ansjer.config import LOGGER
  8. import time
  9. from django.views import View
  10. from Object.IPWeatherObject import WeatherInfo
  11. from Model.models import UidSetModel, CityInformation
  12. from Object.ResponseObject import ResponseObject
  13. from Object.RedisObject import RedisObject
  14. class WeatherView(View):
  15. def get(self, request, *args, **kwargs):
  16. request.encoding = 'utf-8'
  17. operation = kwargs.get('operation')
  18. return self.validation(request.GET, operation, request)
  19. def post(self, request, *args, **kwargs):
  20. request.encoding = 'utf-8'
  21. operation = kwargs.get('operation')
  22. return self.validation(request.POST, operation, request)
  23. def validation(self, request_dict, operation, request):
  24. lang = request_dict.get('lang', 'en')
  25. response = ResponseObject(lang)
  26. if operation == 'get': # 获取天气
  27. return self.get_weather(request_dict, response)
  28. else:
  29. return response.json(414)
  30. @staticmethod
  31. def get_weather(request_dict, response):
  32. """
  33. 获取天气
  34. @param request_dict: 请求参数
  35. @request_dict uid: 设备uid
  36. @param response: 响应对象
  37. @return: response
  38. """
  39. uid = request_dict.get('uid')
  40. if not uid:
  41. return response.json(444, 'uid')
  42. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('tb_city_information_id')
  43. if not uid_set_qs.exists():
  44. return response.json(173)
  45. redis_obj = RedisObject()
  46. city_id = uid_set_qs[0]['tb_city_information_id']
  47. try:
  48. weather = redis_obj.get_data('city_id_{}_weather'.format(city_id))
  49. if weather:
  50. temp, humidity = weather.split('/')
  51. else:
  52. city_obj = WeatherInfo(city_id)
  53. temp, humidity = city_obj.get_city_weather()
  54. if temp and humidity:
  55. redis_obj.set_ex_data('city_id_{}_weather'.format(city_id), '{}/{}'.format(temp, humidity), 600)
  56. if not all([temp, humidity]):
  57. return response.json(10, '获取天气失败')
  58. return response.json(0, {'temp': temp, 'humidity': humidity})
  59. except Exception as e:
  60. print(e)
  61. return response.json(500)