feat:重新初始化

This commit is contained in:
2025-09-23 15:13:29 +08:00
parent de43a551bc
commit 842da15886
31 changed files with 2500 additions and 0 deletions

108
utils/blog_utils.py Normal file
View File

@@ -0,0 +1,108 @@
from fastapi import Request
from models.blog import BlogVisit
# 博客概要字数
BLOG_SUMMARY_COUNT = 100
# 阅读速度 600 字/分钟
READ_SPEED = 600.0
# 博客非统计字符
EXCLUDE_CHARS = [' ', '\n', '\t']
def get_word_count(text: str) -> int:
"""
获取文本字数
:param text: 文本
:return: 字数
"""
count = 0
if not text: # 检查None或空字符串
return count
for char in text:
if char not in EXCLUDE_CHARS:
count += 1
return count
def get_read_duration(word_count: int) -> float:
"""
获取阅读时长 单位:分钟
:param word_count: 文本字数
:return: 阅读时长
"""
return word_count / READ_SPEED
def get_blog_summary(content: str) -> str:
"""
获取简要信息
:param content: 博客内容
:return: 简要信息
"""
if len(content) > BLOG_SUMMARY_COUNT:
return content[:BLOG_SUMMARY_COUNT]
return content
def get_client_ip(request):
"""从请求中获取客户端IP地址"""
x_forwarded_for = request.headers.get("X-Forwarded-For")
if x_forwarded_for:
return x_forwarded_for.split(',')[0]
return request.client.host
def get_user_agent_info(user_agent: str):
"""解析User-Agent获取操作系统和浏览器信息"""
# 使用正则表达式进行更精确的解析
os = "Unknown"
browser = "Unknown"
# 操作系统检测
if "Windows NT" in user_agent:
os = "Windows"
elif "Macintosh" in user_agent:
os = "Mac OS"
elif "Linux" in user_agent:
os = "Linux"
elif "Android" in user_agent:
os = "Android"
elif "iPhone" in user_agent or "iPad" in user_agent:
os = "iOS"
# 浏览器检测
if "Chrome" in user_agent:
browser = "Chrome"
elif "Firefox" in user_agent:
browser = "Firefox"
elif "Safari" in user_agent and "Chrome" not in user_agent:
browser = "Safari"
elif "Edge" in user_agent:
browser = "Edge"
elif "MSIE" in user_agent or "Trident" in user_agent:
browser = "Internet Explorer"
return os, browser
def get_blog_visit(request: Request, blog_id: int) -> BlogVisit:
ip = get_client_ip(request)
user_agent = request.headers.get("User-Agent", "")
os, browser = get_user_agent_info(user_agent)
return BlogVisit(
ip=ip,
os=os,
browser=browser,
uri=request.url.path,
blog_id=blog_id
)