today_weather.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. from datetime import datetime
  2. import requests
  3. import sqlite3
  4. import json
  5. import os
  6. import sys
  7. from weather import all_city
  8. import logging
  9. import django
  10. import time
  11. import random
  12. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  13. sys.path.append(BASE_DIR)
  14. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bigdataAPI.settings')
  15. django.setup()
  16. from apps.Weather.models import District, DayData, HistoryDayData
  17. # # 配置日志级别和格式
  18. # logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  19. # # 创建一个文件处理器,指定日志文件名和写入模式
  20. # os.mkdir("/data/weather/") if not os.path.exists("/data/weather/") else None
  21. # file_handler = logging.FileHandler('/data/weather/app.log')
  22. # file_handler.setLevel(logging.INFO)
  23. # # 创建一个格式化程序,用于定义日志消息的显示方式
  24. # formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  25. # file_handler.setFormatter(formatter)
  26. # # 将文件处理器添加到根日志记录器中
  27. # logging.getLogger('').addHandler(file_handler)
  28. app_id = "69334222"
  29. app_secret = "2u4bHXHD"
  30. province_dict = {
  31. "11": '北京市',
  32. "12": '天津市',
  33. "13": '河北省',
  34. "14": '山西省',
  35. "15": '内蒙古自治区',
  36. "21": '辽宁省',
  37. "22": '吉林省',
  38. "23": '黑龙江省',
  39. "31": '上海市',
  40. "32": '江苏省',
  41. "33": '浙江省',
  42. "34": '安徽省',
  43. "35": '福建省',
  44. "36": '江西省',
  45. "37": '山东省',
  46. "41": '河南省',
  47. "42": '湖北省',
  48. "43": '湖南省',
  49. "44": '广东省',
  50. "45": '广西壮族自治区',
  51. "46": '海南省',
  52. "50": '重庆市',
  53. "51": '四川省',
  54. "52": '贵州省',
  55. "53": '云南省',
  56. "54": '西藏自治区',
  57. "61": '陕西省',
  58. "62": '甘肃省',
  59. "63": '青海省',
  60. "64": '宁夏回族自治区',
  61. "65": '新疆维吾尔自治区'
  62. }
  63. def init_data():
  64. # 导入全部的城市
  65. for k in all_city:
  66. print(k, "-------------")
  67. district = District()
  68. district.city_id = str(k[0])
  69. district.city = k[1]
  70. district.pid = str(k[2])
  71. district.save()
  72. def main():
  73. headers = {
  74. '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',
  75. 'Accept-Language': 'en-US,en;q=0.8',
  76. 'Accept-Encoding': 'gzip, deflate, br',
  77. 'Connection': 'keep-alive',
  78. }
  79. print("up today ....")
  80. day_data = DayData.objects.all()
  81. today_error = 0
  82. # 调用次数统计
  83. day_ct = 0
  84. now = datetime.now()
  85. start_ct_time = now.strftime('%Y-%m-%d %H:%M:%S')
  86. now_hour = now.hour
  87. today_str = datetime.strptime(f'{now.year}-{now.month}-{now.day} 19:00:00', "%Y-%m-%d %H:%M:%S")
  88. for day_obj in day_data:
  89. try:
  90. time_out = False
  91. print(day_obj.cityid)
  92. today_url = f"http://v1.yiketianqi.com/api?unescape=1&version=v62&appid=69334222&appsecret=2ME6U58N&cityid={day_obj.cityid}"
  93. today_response = requests.get(today_url, headers=headers, timeout=10)
  94. if today_response.status_code == 200:
  95. today_data = json.loads(today_response.text)
  96. if "errcode" not in today_data.keys():
  97. day_obj.content = str(today_data)
  98. day_obj.save()
  99. try:
  100. if now_hour == 19:
  101. HistoryDayData.objects.create(
  102. cityid = day_obj.cityid,
  103. content = today_data,
  104. addtime = int(today_str.timestamp())
  105. )
  106. except Exception as e:
  107. print(e, "历史数据入库失败")
  108. else:
  109. print(f"cityid {day_obj.cityid} error_code {today_response.status_code}")
  110. print(f"request fail again : {day_obj.cityid}")
  111. time.sleep(2)
  112. today_response = requests.get(today_url, headers=headers, timeout=5)
  113. day_ct += 1
  114. if today_response.status_code == 200:
  115. today_data = json.loads(today_response.text)
  116. if "errcode" not in today_data.keys():
  117. day_obj.content = str(today_data)
  118. day_obj.save()
  119. print(f"request again success: {day_obj.cityid}")
  120. try:
  121. if now_hour == 20:
  122. HistoryDayData.objects.create(
  123. cityid = day_obj.cityid,
  124. content = today_data,
  125. addtime = int(today_str.timestamp())
  126. )
  127. except Exception as e:
  128. print(e, "历史数据入库失败")
  129. else:
  130. print(f"cityid {day_obj.cityid} error_code {today_response.status_code} again request fail")
  131. print(f"error {today_error}")
  132. today_error += 1
  133. time_out = True
  134. except Exception as e:
  135. print(f"request fail again : {day_obj.cityid} {e.args}")
  136. finally:
  137. day_ct += 1
  138. if time_out:
  139. time.sleep(1)
  140. else:
  141. time.sleep(0.5)
  142. with open("/var/log/bigdata_api/today_count.log", 'a+', encoding='utf-8') as f:
  143. f.write(f"当日天气接口: 开始时间:{start_ct_time} 结束时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} 调用次数:{day_ct} \n")
  144. # 把19点的数据写入历史天气数据中
  145. if __name__ == "__main__":
  146. main()