66 lines
2.0 KiB
Python
66 lines
2.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
import logging
|
|
import os
|
|
from typing import Optional
|
|
|
|
import urllib3
|
|
from fastapi import APIRouter, Request, Query
|
|
from fastapi.responses import Response
|
|
|
|
from favicon_app.routes import favicon_service
|
|
from favicon_app.utils.file_util import FileUtil
|
|
|
|
urllib3.disable_warnings()
|
|
logging.captureWarnings(True)
|
|
logger = logging.getLogger()
|
|
|
|
_icon_root_path = favicon_service.icon_root_path
|
|
_default_icon_path = favicon_service.default_icon_path
|
|
_default_icon_content = favicon_service.default_icon_content
|
|
|
|
# 创建全局服务实例
|
|
_service = favicon_service.FaviconService()
|
|
|
|
# 创建FastAPI路由器
|
|
favicon_router = APIRouter(prefix="", tags=["favicon"])
|
|
|
|
|
|
@favicon_router.get('/icon/')
|
|
@favicon_router.get('/icon')
|
|
@favicon_router.get('/')
|
|
async def get_favicon(
|
|
request: Request,
|
|
url: Optional[str] = Query(None, description="要获取图标的网址"),
|
|
refresh: Optional[str] = Query(None, description="是否刷新缓存,'true'或'1'表示刷新")
|
|
):
|
|
"""获取网站图标"""
|
|
return await _service.get_favicon_handler(request, url, refresh)
|
|
|
|
|
|
@favicon_router.get('/icon/default')
|
|
async def get_default_icon(cache_time: int = Query(_service.time_of_1_days, description="缓存时间")):
|
|
"""获取默认图标"""
|
|
return Response(content=_default_icon_content,
|
|
media_type="image/png",
|
|
headers=_service.get_header("image/png", cache_time))
|
|
|
|
|
|
@favicon_router.get('/icon/count')
|
|
async def get_count():
|
|
"""获取统计数据"""
|
|
return _service.get_count()
|
|
|
|
|
|
@favicon_router.get('/icon/referrer')
|
|
async def get_referrer():
|
|
"""获取请求来源信息"""
|
|
content = 'None'
|
|
path = os.path.join(_icon_root_path, 'referrer.txt')
|
|
if os.path.exists(path):
|
|
try:
|
|
content = FileUtil.read_file(path, mode='r') or 'None'
|
|
except Exception as e:
|
|
logger.error(f"读取referrer文件失败: {e}")
|
|
return Response(content=content, media_type="text/plain")
|