device_manage.py 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import datetime
  2. from smartfarming.models.device import MongoDevice
  3. from kedong.decoration import kedong_deco, PortError
  4. from smartfarming.utils import get_address_by_lntlat, get_weather_info
  5. @kedong_deco(login_required=False)
  6. def weathers(request):
  7. """
  8. 天气接口
  9. 参数
  10. lat 必传(str) 纬度
  11. lng 必传(str) 经度
  12. 返回值:
  13. "data": [
  14. {
  15. "id": 1201,
  16. "province": "新疆维吾尔自治区", 省
  17. "city": "克孜勒苏柯尔克孜自治州", 市
  18. "district": "阿克陶县", 县
  19. "lng": "75.945159", 经度
  20. "lat": "39.147079", 纬度
  21. "at": "31", 温度
  22. "ah": "14", 湿度
  23. "upl_time": "2021-10-25 14:39:48", 时间
  24. "win": "东风", 风向
  25. "win_speed": "1级", 风速
  26. "win_meter": "5km/h", 风力
  27. "wea": "多云", 天气
  28. "visibility": "30km", 能见度
  29. "pressure": "863", 压力
  30. "air": "40", 空气
  31. "air_pm25": "19", 空气PM2.5
  32. "air_level": "优", 空气等级
  33. "air_tips": "空气很好,可以外出活动,呼吸新鲜空气,拥抱大自然!" 空气说明
  34. }
  35. ],
  36. "params": {
  37. "lat": "039.1850853",
  38. "lng": "075.8749465"
  39. }
  40. }
  41. """
  42. lat = request.POST.get('lat', '')
  43. lng = request.POST.get('lng', '')
  44. device_id = request.POST.get('device_id')
  45. if not lat and not lng:
  46. raise PortError('', '未传经纬度')
  47. province, city, district = "", "", ""
  48. if device_id:
  49. try:
  50. instance = MongoDevice.objects.get(device_id=device_id)
  51. province, city, district = instance.province, instance.city, instance.district
  52. if (not city) and district:
  53. city = district
  54. except Exception as e:
  55. pass
  56. if not (province and city):
  57. province, city, district = get_address_by_lntlat(lng, lat)
  58. result = []
  59. weather_info = get_weather_info(lng, lat)
  60. try:
  61. upl_time = weather_info.get('upl_time')
  62. upl_time = datetime.datetime.fromtimestamp(int(upl_time)).strftime("%Y-%m-%d %H:%M:%S")
  63. except Exception as e:
  64. upl_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  65. result.append({
  66. "province": province,
  67. "city": city,
  68. "district": district,
  69. "lng": lng,
  70. "lat": lat,
  71. "at": weather_info.get('at', ''),
  72. "ah": weather_info.get('ah', ''),
  73. "upl_time": upl_time,
  74. "win": weather_info.get('win', ''),
  75. "win_speed": weather_info.get('win_speed', ''),
  76. "win_meter": weather_info.get('win_meter', ''),
  77. "wea": weather_info.get('wea', ''),
  78. "visibility": weather_info.get('visibility', ''),
  79. "pressure": weather_info.get('pressure', ''),
  80. "air": weather_info.get('air', ''),
  81. "air_pm25": weather_info.get('air_pm25', ''),
  82. "air_level": weather_info.get('air_level', ''),
  83. "air_tips": weather_info.get('air_tips', ''),
  84. })
  85. return result