feat:初始化工程
This commit is contained in:
BIN
utils/__pycache__/blog_utils.cpython-312.pyc
Normal file
BIN
utils/__pycache__/blog_utils.cpython-312.pyc
Normal file
Binary file not shown.
BIN
utils/__pycache__/common.cpython-312.pyc
Normal file
BIN
utils/__pycache__/common.cpython-312.pyc
Normal file
Binary file not shown.
58
utils/blog_utils.py
Normal file
58
utils/blog_utils.py
Normal file
@@ -0,0 +1,58 @@
|
||||
from fastapi import Request
|
||||
|
||||
from models.blog import BlogVisit
|
||||
|
||||
|
||||
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
|
||||
)
|
||||
13
utils/common.py
Normal file
13
utils/common.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import re
|
||||
|
||||
|
||||
def camel_to_snake(name: str) -> str:
|
||||
"""将驼峰命名转换为蛇形命名(CamelCase → snake_case)"""
|
||||
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
|
||||
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()
|
||||
|
||||
|
||||
def snake_to_camel(name: str) -> str:
|
||||
"""将蛇形命名转换为驼峰命名(snake_case → CamelCase)"""
|
||||
components = name.split('_')
|
||||
return ''.join(x.title() for x in components)
|
||||
Reference in New Issue
Block a user