apply_weather.py 2.8 KB

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