apply_weather.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from rest_framework.views import APIView
  2. from rest_framework.response import Response
  3. import sqlite3
  4. province_dict = {
  5. "11": '北京市',
  6. "12": '天津市',
  7. "13": '河北省',
  8. "14": '山西省',
  9. "15": '内蒙古自治区',
  10. "21": '辽宁省',
  11. "22": '吉林省',
  12. "23": '黑龙江省',
  13. "31": '上海市',
  14. "32": '江苏省',
  15. "33": '浙江省',
  16. "34": '安徽省',
  17. "35": '福建省',
  18. "36": '江西省',
  19. "37": '山东省',
  20. "41": '河南省',
  21. "42": '湖北省',
  22. "43": '湖南省',
  23. "44": '广东省',
  24. "45": '广西壮族自治区',
  25. "46": '海南省',
  26. "50": '重庆市',
  27. "51": '四川省',
  28. "52": '贵州省',
  29. "53": '云南省',
  30. "54": '西藏自治区',
  31. "61": '陕西省',
  32. "62": '甘肃省',
  33. "63": '青海省',
  34. "64": '宁夏回族自治区',
  35. "65": '新疆维吾尔自治区'
  36. }
  37. class GetWeather(APIView):
  38. def post(self, request):
  39. # 对外提供天气接口,需要提供省,市,区(县)
  40. try:
  41. db = "/data/weather/weather.db"
  42. data = request.data
  43. province = data.get("province")
  44. city = data.get("city")
  45. district = data.get("district")
  46. day_type = data.get("day_type")
  47. conn = sqlite3.connect(db)
  48. cursor = conn.cursor()
  49. table = "day_data" if day_type == "1" else "serven_day_data"
  50. sql = """
  51. select content from ? where province= ? and city = ? and district = ?
  52. """
  53. cursor.execute(sql, (table, province, city, district, ))
  54. result = cursor.fetchone()
  55. if not result:
  56. # 省市正确
  57. sql = """
  58. select content from ? where province= ? and city = ?
  59. """
  60. cursor.execute(sql, (table, province, city, ))
  61. result = cursor.fetchone()
  62. if not result:
  63. # 省正确
  64. sql = """
  65. select id from district where city = ?
  66. """
  67. cursor.execute(sql, province)
  68. provincd_id = cursor.fetchone()
  69. day_data_id = f"{provincd_id}0100000000"
  70. sql = """
  71. select content from ? where id = ?
  72. """
  73. cursor.execute(sql, (table, day_data_id, ))
  74. result = cursor.fetchone()
  75. return Response({"content": result})
  76. except Exception as e:
  77. print(e)
  78. return Response({"msg": "请联系管理员", "code": "50001"})