crond_weather.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import requests
  2. import sqlite3
  3. import json
  4. import os
  5. import sys
  6. from weather import all_city
  7. import logging
  8. import django
  9. import time
  10. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  11. sys.path.append(BASE_DIR)
  12. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bigdataAPI.settings')
  13. django.setup()
  14. from apps.Weather.models import District, DayData, ServerDayData
  15. # 配置日志级别和格式
  16. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  17. # 创建一个文件处理器,指定日志文件名和写入模式
  18. os.mkdir("/data/weather/") if not os.path.exists("/data/weather/") else None
  19. file_handler = logging.FileHandler('/data/weather/app.log')
  20. file_handler.setLevel(logging.INFO)
  21. # 创建一个格式化程序,用于定义日志消息的显示方式
  22. formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  23. file_handler.setFormatter(formatter)
  24. # 将文件处理器添加到根日志记录器中
  25. logging.getLogger('').addHandler(file_handler)
  26. app_id = "69334222"
  27. app_secret = "2u4bHXHD"
  28. province_dict = {
  29. "11": '北京市',
  30. "12": '天津市',
  31. "13": '河北省',
  32. "14": '山西省',
  33. "15": '内蒙古自治区',
  34. "21": '辽宁省',
  35. "22": '吉林省',
  36. "23": '黑龙江省',
  37. "31": '上海市',
  38. "32": '江苏省',
  39. "33": '浙江省',
  40. "34": '安徽省',
  41. "35": '福建省',
  42. "36": '江西省',
  43. "37": '山东省',
  44. "41": '河南省',
  45. "42": '湖北省',
  46. "43": '湖南省',
  47. "44": '广东省',
  48. "45": '广西壮族自治区',
  49. "46": '海南省',
  50. "50": '重庆市',
  51. "51": '四川省',
  52. "52": '贵州省',
  53. "53": '云南省',
  54. "54": '西藏自治区',
  55. "61": '陕西省',
  56. "62": '甘肃省',
  57. "63": '青海省',
  58. "64": '宁夏回族自治区',
  59. "65": '新疆维吾尔自治区'
  60. }
  61. def init_data():
  62. # 导入全部的城市
  63. for k in all_city:
  64. print(k, "-------------")
  65. district = District()
  66. district.city_id = str(k[0])
  67. district.city = k[1]
  68. district.pid = str(k[2])
  69. district.save()
  70. def main():
  71. logging.warning("up today ...")
  72. day_data = DayData.objects.all()
  73. for day_obj in day_data:
  74. today_url = f"http://v0.yiketianqi.com/api?unescape=1&version=v62&appid=69334222&appsecret=2u4bHXHD&cityid={day_obj.cityid}"
  75. today_response = requests.get(today_url, timeout=5)
  76. try:
  77. today_data = json.loads(today_response.text)
  78. if "errcode" not in today_data.keys():
  79. day_obj.content = str(today_data)
  80. day_obj.save()
  81. except Exception as e:
  82. logging.warning(f"cityid {day_obj.cityid} error {e} {today_response.text}")
  83. logging.warning("over today ...")
  84. logging.warning("up server day ...")
  85. server_days = ServerDayData.objects.all()
  86. for server_day_obj in server_days:
  87. server_day_url = f"http://v0.yiketianqi.com/api?unescape=1&version=v91&appid=69334222&appsecret=2u4bHXHD&cityid={server_day_obj.cityid}&ext=hours,aqi,life"
  88. server_day_response = requests.get(server_day_url, timeout=5)
  89. try:
  90. server_day_data = json.loads(server_day_response.text)
  91. if "errcode" not in server_day_data.keys():
  92. server_day_obj.content = str(server_day_data)
  93. server_day_obj.save()
  94. except Exception as e:
  95. logging.warning(f"cityid {server_day_obj.cityid} error {e} {today_response.text}")
  96. logging.warning("over server day ...")
  97. """
  98. district = District.objects.all()
  99. # init_data()
  100. logging.warning("up...")
  101. results = District.objects.filter(id__gt = 31)
  102. # 更新数据
  103. for row in results:
  104. temp = row.city # 东城区
  105. city_id = row.city_id # 110101000000
  106. pid = row.pid # 110100000000
  107. province_id = city_id[:2]
  108. province = province_dict.get(province_id)
  109. if len(pid) == 2 and temp == "市辖区":
  110. # 处理 市辖区 只有两级,区为空
  111. city = province
  112. district = "市辖区"
  113. elif len(pid) ==2 and temp != "市辖区":
  114. # 三级 省 市 区(县)
  115. city = temp
  116. district = ""
  117. else:
  118. dis = District.objects.get(city_id=pid)
  119. city = dis.city
  120. district = temp
  121. try:
  122. today_url = f"http://v0.yiketianqi.com/api?unescape=1&version=v62&appid=69334222&appsecret=2u4bHXHD&adcode={city_id}"
  123. today_response = requests.get(today_url, timeout=5)
  124. today_data = json.loads(today_response.text)
  125. if "errcode" not in today_data.keys():
  126. cityid = today_data.get("cityid", "")
  127. DayData.objects.update_or_create(
  128. cityid=cityid,
  129. defaults={
  130. "cityid": cityid,
  131. "province": province,
  132. "city": city,
  133. "district": district,
  134. "content": str(today_data)
  135. }
  136. )
  137. server_day_url = f"http://v0.yiketianqi.com/api?unescape=1&version=v91&appid={app_id}&appsecret={app_secret}&adcode={city_id}&ext=hours,aqi,life"
  138. server_day_response = requests.get(server_day_url, timeout=5)
  139. server_day_data = json.loads(server_day_response.text)
  140. if "errcode" not in server_day_data.keys():
  141. cityid = today_data.get("cityid", "")
  142. ServerDayData.objects.update_or_create(
  143. cityid=cityid,
  144. defaults={
  145. "cityid": cityid,
  146. "province": province,
  147. "city": city,
  148. "district": district,
  149. "content": str(server_day_data)
  150. }
  151. )
  152. except Exception as e:
  153. print(e)
  154. logging.warning("over...")
  155. """
  156. if __name__ == "__main__":
  157. main()