WeatherControl.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. class WeatherView(View):
  14. def get(self, request, *args, **kwargs):
  15. request.encoding = 'utf-8'
  16. operation = kwargs.get('operation')
  17. return self.validation(request.GET, operation, request)
  18. def post(self, request, *args, **kwargs):
  19. request.encoding = 'utf-8'
  20. operation = kwargs.get('operation')
  21. return self.validation(request.POST, operation, request)
  22. def validation(self, request_dict, operation, request):
  23. lang = request_dict.get('lang', 'en')
  24. response = ResponseObject(lang)
  25. if operation == 'get': # 获取天气
  26. return self.get_weather(request_dict, response)
  27. else:
  28. return response.json(414)
  29. @staticmethod
  30. def get_weather(request_dict, response):
  31. """
  32. 获取天气
  33. @param request_dict: 请求参数
  34. @request_dict uid: 设备uid
  35. @param response: 响应对象
  36. @return: response
  37. """
  38. uid = request_dict.get('uid')
  39. if not uid:
  40. return response.json(444, 'uid')
  41. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('tb_city_information_id')
  42. if not uid_set_qs.exists():
  43. return response.json(173)
  44. try:
  45. city_obj = WeatherInfo(uid_set_qs[0]['tb_city_information_id'])
  46. temp, humidity = city_obj.get_city_weather()
  47. return response.json(0, {'temp': temp, 'humidity': humidity})
  48. except Exception as e:
  49. print(e)
  50. return response.json(500)