crond_weather.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. import random
  11. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  12. sys.path.append(BASE_DIR)
  13. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bigdataAPI.settings')
  14. django.setup()
  15. from apps.Weather.models import District, DayData, ServerDayData
  16. # 配置日志级别和格式
  17. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  18. # 创建一个文件处理器,指定日志文件名和写入模式
  19. os.mkdir("/data/weather/") if not os.path.exists("/data/weather/") else None
  20. file_handler = logging.FileHandler('/data/weather/app.log')
  21. file_handler.setLevel(logging.INFO)
  22. # 创建一个格式化程序,用于定义日志消息的显示方式
  23. formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  24. file_handler.setFormatter(formatter)
  25. # 将文件处理器添加到根日志记录器中
  26. logging.getLogger('').addHandler(file_handler)
  27. app_id = "69334222"
  28. app_secret = "2u4bHXHD"
  29. province_dict = {
  30. "11": '北京市',
  31. "12": '天津市',
  32. "13": '河北省',
  33. "14": '山西省',
  34. "15": '内蒙古自治区',
  35. "21": '辽宁省',
  36. "22": '吉林省',
  37. "23": '黑龙江省',
  38. "31": '上海市',
  39. "32": '江苏省',
  40. "33": '浙江省',
  41. "34": '安徽省',
  42. "35": '福建省',
  43. "36": '江西省',
  44. "37": '山东省',
  45. "41": '河南省',
  46. "42": '湖北省',
  47. "43": '湖南省',
  48. "44": '广东省',
  49. "45": '广西壮族自治区',
  50. "46": '海南省',
  51. "50": '重庆市',
  52. "51": '四川省',
  53. "52": '贵州省',
  54. "53": '云南省',
  55. "54": '西藏自治区',
  56. "61": '陕西省',
  57. "62": '甘肃省',
  58. "63": '青海省',
  59. "64": '宁夏回族自治区',
  60. "65": '新疆维吾尔自治区'
  61. }
  62. def init_data():
  63. # 导入全部的城市
  64. for k in all_city:
  65. print(k, "-------------")
  66. district = District()
  67. district.city_id = str(k[0])
  68. district.city = k[1]
  69. district.pid = str(k[2])
  70. district.save()
  71. def main():
  72. headers = {
  73. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299',
  74. 'Accept-Language': 'en-US,en;q=0.8',
  75. 'Accept-Encoding': 'gzip, deflate, br',
  76. 'Connection': 'keep-alive',
  77. }
  78. day_data = DayData.objects.all()
  79. today_error = 0
  80. for day_obj in day_data:
  81. time_out = False
  82. logging.warning(day_obj.cityid)
  83. today_url = f"http://v0.yiketianqi.com/api?unescape=1&version=v62&appid=69334222&appsecret=2ME6U58N&cityid={day_obj.cityid}"
  84. today_response = requests.get(today_url, headers=headers, timeout=5)
  85. try:
  86. if today_response.status_code == 200:
  87. today_data = json.loads(today_response.text)
  88. if "errcode" not in today_data.keys():
  89. day_obj.content = str(today_data)
  90. day_obj.save()
  91. else:
  92. logging.warning(f"cityid {day_obj.cityid} error_code {today_response.status_code}")
  93. logging.warning(f"request fail again : {day_obj.cityid}")
  94. time.sleep(2)
  95. today_response = requests.get(today_url, headers=headers, timeout=5)
  96. if today_response.status_code == 200:
  97. today_data = json.loads(today_response.text)
  98. if "errcode" not in today_data.keys():
  99. day_obj.content = str(today_data)
  100. day_obj.save()
  101. logging.warning(f"request again success: {day_obj.cityid}")
  102. else:
  103. logging.warning(f"cityid {day_obj.cityid} error_code {today_response.status_code} again request fail")
  104. logging.error(f"error {today_error}")
  105. today_error += 1
  106. time_out = True
  107. except Exception as e:
  108. logging.warning(f"request fail again : {day_obj.cityid} {e.args}")
  109. if time_out:
  110. time.sleep(5)
  111. else:
  112. time.sleep(2)
  113. server_error = 0
  114. logging.warning("up server day ...")
  115. server_days = ServerDayData.objects.all()
  116. for server_day_obj in server_days:
  117. time_out_k = False
  118. logging.warning(server_day_obj.cityid)
  119. server_day_url = f"http://v0.yiketianqi.com/api?unescape=1&version=v91&appid=69334222&appsecret=2ME6U58N&cityid={server_day_obj.cityid}&ext=hours,aqi,life"
  120. server_day_response = requests.get(server_day_url, headers=headers, timeout=5)
  121. try:
  122. if server_day_response.status_code == 200:
  123. server_day_data = json.loads(server_day_response.text)
  124. if "errcode" not in server_day_data.keys():
  125. server_day_obj.content = str(server_day_data)
  126. server_day_obj.save()
  127. else:
  128. time.sleep(2)
  129. logging.warning(f"cityid {day_obj.cityid} error_code {server_day_response.status_code}")
  130. logging.warning(f"request fail again : {server_day_obj.cityid}")
  131. server_day_response = requests.get(server_day_url, headers=headers, timeout=5)
  132. if server_day_response.status_code == 200:
  133. server_day_data = json.loads(server_day_response.text)
  134. if "errcode" not in server_day_data.keys():
  135. server_day_obj.content = str(server_day_data)
  136. server_day_obj.save()
  137. logging.warning(f"request again success: {server_day_obj.cityid}")
  138. else:
  139. logging.warning(f"cityid {day_obj.cityid} error_code {server_day_response.status_code} again request afil")
  140. logging.error(f"error {server_error}")
  141. server_error += 1
  142. time_out_k = True
  143. except Exception as e:
  144. logging.warning(f"request fail again : {server_day_obj.cityid} {e.args}")
  145. if time_out_k:
  146. time.sleep(5)
  147. else:
  148. time.sleep(2)
  149. """
  150. district = District.objects.all()
  151. # init_data()
  152. logging.warning("up...")
  153. results = District.objects.filter(id__gt = 31)
  154. # 更新数据
  155. for row in results:
  156. temp = row.city # 东城区
  157. city_id = row.city_id # 110101000000
  158. pid = row.pid # 110100000000
  159. province_id = city_id[:2]
  160. province = province_dict.get(province_id)
  161. if len(pid) == 2 and temp == "市辖区":
  162. # 处理 市辖区 只有两级,区为空
  163. city = province
  164. district = "市辖区"
  165. elif len(pid) ==2 and temp != "市辖区":
  166. # 三级 省 市 区(县)
  167. city = temp
  168. district = ""
  169. else:
  170. dis = District.objects.get(city_id=pid)
  171. city = dis.city
  172. district = temp
  173. try:
  174. today_url = f"http://v0.yiketianqi.com/api?unescape=1&version=v62&appid=69334222&appsecret=2u4bHXHD&adcode={city_id}"
  175. today_response = requests.get(today_url, timeout=5)
  176. today_data = json.loads(today_response.text)
  177. if "errcode" not in today_data.keys():
  178. cityid = today_data.get("cityid", "")
  179. DayData.objects.update_or_create(
  180. cityid=cityid,
  181. defaults={
  182. "cityid": cityid,
  183. "province": province,
  184. "city": city,
  185. "district": district,
  186. "content": str(today_data)
  187. }
  188. )
  189. 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"
  190. server_day_response = requests.get(server_day_url, timeout=5)
  191. server_day_data = json.loads(server_day_response.text)
  192. if "errcode" not in server_day_data.keys():
  193. cityid = today_data.get("cityid", "")
  194. ServerDayData.objects.update_or_create(
  195. cityid=cityid,
  196. defaults={
  197. "cityid": cityid,
  198. "province": province,
  199. "city": city,
  200. "district": district,
  201. "content": str(server_day_data)
  202. }
  203. )
  204. except Exception as e:
  205. print(e)
  206. logging.warning("over...")
  207. """
  208. if __name__ == "__main__":
  209. main()