apply_weather.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. username = data.get("username")
  53. password = data.get("password")
  54. sql = """
  55. select * from user where username = ? and password = ?
  56. """
  57. cursor.execute(sql, (username, password,))
  58. user = cursor.fetchone()
  59. if not user:
  60. return Response({"msg":"认证失败", "code": 400})
  61. table = "day_data" if day_type == "1" else "serven_day_data"
  62. table = "day_data" if day_type == "1" else "server_day_data"
  63. sql = f"select content from {table} where province = '{province}' and city ='{city}' and district ='{district}'"
  64. cursor.execute(sql)
  65. result = cursor.fetchone()
  66. if not result:
  67. # 省市正确
  68. sql = f"select content from {table} where province= '{province}' and city = '{city}'"
  69. cursor.execute(sql)
  70. result = cursor.fetchone()
  71. if not result:
  72. # 省正确
  73. sql = f"select content from {table} where province = '{province}'"
  74. cursor.execute(sql)
  75. result = cursor.fetchone()
  76. if result:
  77. return Response({"content": result[0], "msg": "success", "code": 200})
  78. else:
  79. return Response({"content": "", "msg": "success", "code": 500})
  80. except Exception as e:
  81. logging.info(e)
  82. return Response({"msg": "请联系管理员", "code": "50001"})
  83. class TestAPI(APIView):
  84. def post(self, request):
  85. return Response({"test": 111})