feat: v2.2.0 智能新闻更新和布局优化
- 实现每日首次访问自动更新新闻功能 - 每个网站获取3条一周内的新闻 - 新闻模块放置在左侧主栏 - 相似推荐移至右侧边栏 - 自动去重防止重复新闻
This commit is contained in:
64
app.py
64
app.py
@@ -116,6 +116,70 @@ def create_app(config_name='default'):
|
||||
site.view_count += 1
|
||||
db.session.commit()
|
||||
|
||||
# 智能新闻更新:检查今天是否已更新过新闻
|
||||
from datetime import date
|
||||
today = date.today()
|
||||
|
||||
# 检查该网站最新一条新闻的创建时间
|
||||
latest_news = News.query.filter_by(
|
||||
site_id=site.id
|
||||
).order_by(News.created_at.desc()).first()
|
||||
|
||||
# 判断是否需要更新新闻
|
||||
need_update = False
|
||||
if not latest_news:
|
||||
# 没有任何新闻,需要获取
|
||||
need_update = True
|
||||
elif latest_news.created_at.date() < today:
|
||||
# 最新新闻不是今天创建的,需要更新
|
||||
need_update = True
|
||||
|
||||
# 如果需要更新,自动获取最新新闻
|
||||
if need_update:
|
||||
api_key = app.config.get('BOCHA_API_KEY')
|
||||
if api_key:
|
||||
try:
|
||||
# 创建新闻搜索器
|
||||
searcher = NewsSearcher(api_key)
|
||||
|
||||
# 获取新闻(限制3条,一周内的)
|
||||
news_items = searcher.search_site_news(
|
||||
site_name=site.name,
|
||||
site_url=site.url,
|
||||
count=3,
|
||||
freshness='oneWeek'
|
||||
)
|
||||
|
||||
# 保存新闻到数据库
|
||||
if news_items:
|
||||
for item in news_items:
|
||||
# 检查是否已存在(根据URL去重)
|
||||
existing = News.query.filter_by(
|
||||
site_id=site.id,
|
||||
url=item['url']
|
||||
).first()
|
||||
|
||||
if not existing:
|
||||
news = News(
|
||||
site_id=site.id,
|
||||
title=item['title'],
|
||||
content=item.get('summary') or item.get('snippet', ''),
|
||||
url=item['url'],
|
||||
source_name=item.get('site_name', ''),
|
||||
source_icon=item.get('site_icon', ''),
|
||||
published_at=item.get('published_at'),
|
||||
news_type='Search Result',
|
||||
is_active=True
|
||||
)
|
||||
db.session.add(news)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
except Exception as e:
|
||||
# 获取新闻失败,不影响页面显示
|
||||
print(f"自动获取新闻失败:{str(e)}")
|
||||
db.session.rollback()
|
||||
|
||||
# 获取该网站的相关新闻(最多显示5条)
|
||||
news_list = News.query.filter_by(
|
||||
site_id=site.id,
|
||||
|
||||
Reference in New Issue
Block a user