修改成在启动的时候可以自动初始化数据

This commit is contained in:
2026-03-30 22:01:47 +08:00
parent a10a5a176b
commit 97c97b7bae
5 changed files with 60 additions and 45 deletions
+35 -39
View File
@@ -1,46 +1,42 @@
import requests
import json
# 请将此处的 URL 替换为您实际的 API 基础域名
api_url = "http://10.252.130.135:8000/api/v1/sources/"
from app.database import SessionLocal
from app.crud.crud_source import create
from app.models.models import SourceType
from app.schemas.source_schema import InfoSourceCreate
# 请求头
headers = {
"Content-Type": "application/json",
# "Authorization": "Bearer YOUR_TOKEN" # 如果接口需要鉴权,请取消注释并填入 Token
}
# 解析后的数据源列表
sources_data = [
{"name": "今日头条", "url": "toutiao"},
{"name": "百度热搜", "url": "baidu"},
{"name": "华尔街见闻", "url": "wallstreetcn-hot"},
{"name": "澎湃新闻", "url": "thepaper"},
{"name": "bilibili 热搜", "url": "bilibili-hot-search"},
{"name": "财联社热门", "url": "cls-hot"},
{"name": "凤凰网", "url": "ifeng"},
{"name": "贴吧", "url": "tieba"},
{"name": "微博", "url": "weibo"},
{"name": "抖音", "url": "douyin"},
{"name": "知乎", "url": "zhihu"}
]
def init():
# 遍历数据并发送 POST 请求
for item in sources_data:
payload = {
"source_name": item["name"],
"source_type": "HOT_TREND",
"home_url": item["url"],
"is_enabled": True
}
# 解析后的数据源列表
sources_data = [
{"name": "今日头条", "url": "toutiao"},
{"name": "百度热搜", "url": "baidu"},
{"name": "华尔街见闻", "url": "wallstreetcn-hot"},
{"name": "澎湃新闻", "url": "thepaper"},
{"name": "bilibili 热搜", "url": "bilibili-hot-search"},
{"name": "财联社热门", "url": "cls-hot"},
{"name": "凤凰网", "url": "ifeng"},
{"name": "贴吧", "url": "tieba"},
{"name": "微博", "url": "weibo"},
{"name": "抖音", "url": "douyin"},
{"name": "知乎", "url": "zhihu"}
]
try:
response = requests.post(api_url, headers=headers, data=json.dumps(payload))
if response.status_code in (200, 201):
print(f"✅ 成功创建: {item['name']}")
else:
print(f"❌ 创建失败: {item['name']} - 状态码: {response.status_code} - 详情: {response.text}")
except Exception as e:
print(f"⚠️ 请求异常: {item['name']} - 错误: {e}")
# 遍历数据并发送 POST 请求
for item in sources_data:
try:
with SessionLocal() as db:
print("执行完毕!")
create(db, InfoSourceCreate(
source_name=item["name"],
source_type=SourceType.HOT_TREND,
home_url=item["url"],
is_enabled=True
))
print(f"创建订阅源{item['name']}")
except Exception as e:
print(f"⚠️ 请求异常: {item['name']} - 错误: {e}")