from apscheduler.schedulers.background import BackgroundScheduler from flask import Flask import time import random import requests from flask_cors import CORS app = Flask(__name__) CORS(app, supports_credentials=True) cache = set() scheduler = BackgroundScheduler() def init_scheduler(): def clear_cache(): """清空缓存并记录日志""" cache.clear() print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 缓存已清空") scheduler.add_job(clear_cache, 'cron', hour=0) scheduler.start() def fetch(api): """调用百度热搜 API (示例接口,需替换实际 API Key) [6](@ref)""" url = api[1]['url'] hotList = api[1]['hot'] random.shuffle(hotList) hot = hotList[0] try: res = requests.get(url + hot) if res.json()['code'] == 200: return res.json()['data'][:10] except Exception: return [] @app.route("/hot") def get_random_hot_searches(): """随机调用平台接口并过滤缓存数据""" apis = [ ["hot.nntool.cc", {'url': "https://hotapi.nntool.cc/", 'hot': ["weibo", "douyin", "baidu", "toutiao", "thepaper", "qq-news", "zhihu"]}] ] random.shuffle(apis) # 随机打乱接口顺序 hots = fetch(apis[0]) for hot in hots: if hot['title'] in cache: continue else: cache.add(hot['title']) return {'code': 200, 'data': [hot]} return [{"title": "所有平台数据均重复或无数据", "source": "system"}] if __name__ == "__main__": # init_scheduler() app.run(debug=True)