WeatherControl.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # -*- coding: utf-8 -*-
  2. """
  3. @Author : peng
  4. @Time : 2023-8-18 10:45:46
  5. @File :WeatherControl.py
  6. """
  7. import datetime
  8. from Ansjer.config import CONFIG_INFO, CONFIG_CN
  9. from django.views import View
  10. from Object.IPWeatherObject import WeatherInfo, OpenWeatherMap
  11. from Model.models import UidSetModel, IPAddr
  12. from Object.ResponseObject import ResponseObject
  13. from Object.RedisObject import RedisObject
  14. from Service.CommonService import CommonService
  15. class WeatherView(View):
  16. def get(self, request, *args, **kwargs):
  17. request.encoding = 'utf-8'
  18. operation = kwargs.get('operation')
  19. return self.validation(request.GET, operation)
  20. def post(self, request, *args, **kwargs):
  21. request.encoding = 'utf-8'
  22. operation = kwargs.get('operation')
  23. return self.validation(request.POST, operation)
  24. def validation(self, request_dict, operation):
  25. lang = request_dict.get('lang', 'en')
  26. response = ResponseObject(lang)
  27. if operation == 'get': # 获取天气
  28. return self.get_weather(request_dict, response)
  29. else:
  30. return response.json(414)
  31. @staticmethod
  32. def get_weather(request_dict, response):
  33. """
  34. 获取天气
  35. @param request_dict: 请求参数
  36. @request_dict uid: 设备uid
  37. @param response: 响应对象
  38. @return: response
  39. """
  40. uid = request_dict.get('uid')
  41. if not uid:
  42. return response.json(444, 'uid')
  43. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('tb_city_information_id', 'ip')
  44. if not uid_set_qs.exists():
  45. return response.json(173)
  46. try:
  47. # 根据服务器配置使用不同的服务, 国内:阿里云墨迹天气, 测试,国外:OpenWeatherMap
  48. if CONFIG_INFO == CONFIG_CN:
  49. city_id = uid_set_qs[0]['tb_city_information_id']
  50. if city_id == 0:
  51. return response.json(10, '请更新设备影子地区信息')
  52. today = datetime.datetime.today()
  53. now_time = datetime.datetime(today.year, today.month, today.day, today.hour)
  54. time_stamp = CommonService.str_to_timestamp(now_time.strftime('%Y-%m-%d %H:%M:%S'))
  55. key = 'city_id_{}_{}_weather'.format(city_id, time_stamp)
  56. redis_obj = RedisObject()
  57. weather = redis_obj.get_data(key)
  58. if weather:
  59. temp, humidity = weather.split('/')
  60. else:
  61. city_obj = WeatherInfo(city_id)
  62. temp, humidity = city_obj.get_city_weather()
  63. if temp and humidity:
  64. redis_obj.set_ex_data(key, '{}/{}'.format(temp, humidity), 3600)
  65. else:
  66. ip = uid_set_qs[0]['ip']
  67. ip_addr_qs = IPAddr.objects.filter(ip=ip, is_geoip2=True).values('lat', 'lon')
  68. if not ip_addr_qs.exists():
  69. return response.json(173)
  70. lat, lon = ip_addr_qs[0]['lat'], ip_addr_qs[0]['lon']
  71. open_weather_map = OpenWeatherMap(lat, lon)
  72. temp, humidity = open_weather_map.get_weather()
  73. if temp is None and humidity is None:
  74. return response.json(10, '获取天气失败')
  75. return response.json(0, {'temp': temp, 'humidity': humidity})
  76. except Exception as e:
  77. print(e)
  78. return response.json(500)