hxxl/app.py
2024-12-02 12:49:54 +08:00

166 lines
5.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from datetime import datetime
import json
import os
import requests
from flask import Flask, render_template, abort, jsonify, request, send_from_directory
# 设置 Flask 应用
app = Flask(__name__, static_url_path="", static_folder="static")
app.template_folder = "templates"
# Strapi API 基础 URL 和 API 令牌
STRAPI_BASE_URL = "http://116.204.119.171:8099" # 请替换为您的 Strapi API 地址
STRAPI_API_TOKEN = "156ac348bb6f633eb2b6ebf58757dceae9b949a2a03fae6ad7ea9a5f49b61cc355bb3447533c0488044cb46f2612a22d15781c0eca1028756637d108cd42d039960ad12bf811642c8491d2c198708fe0ea014d793974b64e1d62c76356950f5546dc24653776f144b5a0c47682bd76a7dfd97cfc7e255ad1d6b10b13f7ffc154" # 请替换为您的实际 API 令牌
# 通用数据请求方法
def fetch_data(endpoint, params=None):
"""
从 Strapi 获取数据,使用通用函数来简化请求。
添加异常处理,捕获 JSONDecodeError 并返回 None。
"""
headers = {"Authorization": f"Bearer {STRAPI_API_TOKEN}"}
try:
# 发起 GET 请求
response = requests.get(
f"{STRAPI_BASE_URL}/api/{endpoint}", headers=headers, params=params
)
# 检查响应是否成功
if response.status_code == 200:
try:
# 尝试解析 JSON 数据
return response.json()
except json.JSONDecodeError:
# 如果解析失败,打印错误并返回 None
print(f"Error decoding JSON from {endpoint}: {response.text}")
return None
else:
# 如果请求失败,打印错误状态码
print(f"Error fetching {endpoint}: {response.status_code}")
return None
except requests.exceptions.RequestException as e:
# 捕获请求异常,如连接问题等
print(f"Request error: {e}")
return None
# 动态页面路由
@app.route("/<page_name>")
def render_page(page_name):
html_template = page_name
htm_template = page_name
if os.path.exists(os.path.join(app.template_folder, html_template)):
return render_template(html_template)
elif os.path.exists(os.path.join(app.template_folder, htm_template)):
return render_template(htm_template)
else:
abort(404)
# 动态页面路由
# @app.route('/m/<path:path>')
# def render_page_m(path):
# page_path = path
# html_template = f"{page_path}"
# htm_template = f"{page_path}"
# # 检查是否在 templates 目录中存在对应的 HTML 模板文件
# if os.path.exists(os.path.join(app.template_folder, html_template)):
# return render_template(html_template)
# elif os.path.exists(os.path.join(app.template_folder, htm_template)):
# return render_template(htm_template)
# # 直接转发到 static 目录中的静态资源文件
# return send_from_directory(app.static_folder, page_path)
# 首页路由 - 获取轮播图和新闻内容以渲染首页
@app.route("/info.php-9.html")
def info():
type = request.args.get("type")
# 通过 fetch_data 获取前 3 条 hxkjnewss 数据,使用 populate 参数来加载关联数据
params = {
"pagination[page]": 1,
"pagination[pageSize]": 100,
"populate": "*",
}
# 如果获取到的存在就这么做
if type:
params["filters[type][$eq]"] = type
examples = fetch_data("examples", params=params)
if not examples:
examples = []
else:
examples = examples["data"]
# 为每个 data 对象拼接图片属性
for item in examples:
# 拼接主要图片的 URL假设 `img` 是包含图片的字段
item["image_url"] = (
STRAPI_BASE_URL + item["img"][0]["url"]
if item.get("img") and item["img"][0].get("url")
else None
)
# 将提取的数据传递给模板
return render_template("info.php-9.html", examples=examples)
# 详情页路由
@app.route("/info_detail")
def info_detail():
id = request.args.get("id")
# 获取特定 ID 的详细信息
detail = fetch_data(f"examples/{id}", params={"populate": "*"})
if not detail:
detail = {}
else:
detail = detail["data"]
detail["image_url"] = (
STRAPI_BASE_URL + detail["img"][0]["url"]
if detail.get("img") and detail["img"][0].get("url")
else None
)
return render_template("info_detail.html", detail=detail)
# 首页路由 - 获取轮播图和新闻内容以渲染首页
@app.route("/")
def home():
# 通过 fetch_data 获取前 3 条 hxkjnewss 数据,使用 populate 参数来加载关联数据
data = fetch_data(
"hnewss",
params={"pagination[page]": 1, "pagination[pageSize]": 3, "populate": "*"},
)
# 提取新闻条目的重要字段
news_items = []
if data and "data" in data:
for item in data["data"]:
created_at = item["createdAt"]
created_at_formatted = datetime.strptime(
created_at, "%Y-%m-%dT%H:%M:%S.%fZ"
).strftime("%Y-%m-%d")
news_item = {
"id": item["id"],
"title": item["title"],
"content": item["content"],
"detail": item["detail"],
"createdAt": created_at_formatted,
# 拼接完整的图片 URL
"image_url": (
STRAPI_BASE_URL + item["image"]["url"]
if item.get("image")
else None
),
}
news_items.append(news_item)
# 将提取的数据传递给模板
return render_template("index.html", news_items=news_items)
if __name__ == "__main__":
app.run(debug=True)