fix: add async cache to async operations and sync cache (stdlib) for sync operations

This commit is contained in:
austnv
2026-06-14 23:23:05 +03:00
parent 5d221415cc
commit ccf99af7e1
4 changed files with 39 additions and 17 deletions
+18 -9
View File
@@ -3,12 +3,15 @@ from typing import Optional, Dict, Any, Tuple
from bs4 import BeautifulSoup
from pydantic import BaseModel, Field
from fastapi import APIRouter, Request
from functools import lru_cache
from httpx import AsyncClient
from async_lru import alru_cache
from functools import lru_cache
import asyncio
import logging
logging.basicConfig(level=logging.INFO)
@@ -64,6 +67,7 @@ class IPInfo:
def __init__(self, html: str):
self._data = self._parse(html)
@lru_cache(maxsize=1000)
def _parse(self, html: str) -> Optional[IPInfoModel]:
"""Парсит HTML и возвращает модель"""
soup = BeautifulSoup(html, 'html.parser')
@@ -168,7 +172,14 @@ class IPInfo:
router = APIRouter(prefix='/api/v1', tags=['ip'])
@lru_cache
@alru_cache(maxsize=1000, ttl=86400)
async def get_ip_info(ip: str, user_agent: str):
"""Асинхронная функция для получения информации об IP с кешированием."""
async with AsyncClient(headers={'User-Agent': user_agent}) as client:
response = await client.get(f'https://ipinfo.io/{ip}')
return response.text
@router.get('/ip')
async def get_ip(request: Request):
forwarded = request.headers.get('X-Forwarded-For')
@@ -180,11 +191,9 @@ async def get_ip(request: Request):
else:
client_ip = request.client.host
async with AsyncClient(headers={'User-Agent': user_agent}) as client:
response = await client.get(f'https://ipinfo.io/{client_ip}')
html = response.text
ipinfo = IPInfo(html)
logging.info(ipinfo._data)
html = await get_ip_info(client_ip, user_agent)
return ipinfo.dict()
result = await asyncio.to_thread(lambda: IPInfo(html).dict())
logging.info(result)
return result