68 lines
2.1 KiB
Python
68 lines
2.1 KiB
Python
# -*- coding: utf-8 -*-
|
||
|
||
import logging
|
||
import os
|
||
from typing import Optional
|
||
|
||
import urllib3
|
||
from fastapi import APIRouter, Request, Query, BackgroundTasks
|
||
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,
|
||
bg_tasks: BackgroundTasks,
|
||
url: Optional[str] = Query(None, description="网址:eg. https://www.baidu.com"),
|
||
refresh: Optional[str] = Query(None, include_in_schema=False),
|
||
sync: Optional[str] = Query('false', description="是否使用同步方式获取")
|
||
):
|
||
"""获取网站图标"""
|
||
return await _service.get_favicon_handler(request, bg_tasks, url, refresh, sync)
|
||
|
||
|
||
@favicon_router.get('/icon/default')
|
||
async def get_default_icon(cache_time: int = Query(_service.time_of_1_days, include_in_schema=False)):
|
||
"""获取默认图标"""
|
||
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', include_in_schema=False)
|
||
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")
|