60 lines
1.6 KiB
Python
60 lines
1.6 KiB
Python
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):
|
|
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'])
|
|
res = {'code': 200, 'data': [hot]}
|
|
print("返回热搜词"+str(hot['title']))
|
|
return res
|
|
return [{"title": "所有平台数据均重复或无数据", "source": "system"}]
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# init_scheduler()
|
|
app.run(host="0.0.0.0", port="5000")
|