fix: add async cache to async operations and sync cache (stdlib) for sync operations
This commit is contained in:
+18
-9
@@ -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
|
||||
+8
-7
@@ -1,15 +1,16 @@
|
||||
from fastapi import APIRouter
|
||||
from functools import lru_cache
|
||||
import aiofiles
|
||||
import json
|
||||
import asyncio
|
||||
from async_lru import alru_cache
|
||||
|
||||
router = APIRouter(prefix='/api/v1', tags=['tariffs'])
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def get_tariffs_sync():
|
||||
with open('data/tariffs.json', 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
@alru_cache(maxsize=1, ttl=86400)
|
||||
async def get_tariffs_sync():
|
||||
async with aiofiles.open('data/tariffs.json', 'r', encoding='utf-8') as f:
|
||||
content = await f.read()
|
||||
return json.loads(content)
|
||||
|
||||
@router.get('/tariffs')
|
||||
async def get_tariffs():
|
||||
return await asyncio.to_thread(get_tariffs_sync)
|
||||
return await get_tariffs_sync()
|
||||
Reference in New Issue
Block a user