refactor(api): use Annotated-style dependency injection
This commit is contained in:
@@ -6,10 +6,13 @@ from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
import ipaddress
|
||||
from typing import Annotated
|
||||
|
||||
from app.config import settings
|
||||
from app.helpers.geoip_helper import GeoIPHelper
|
||||
|
||||
from fastapi import Depends, Request
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_geoip_helper() -> GeoIPHelper:
|
||||
@@ -26,7 +29,7 @@ def get_geoip_helper() -> GeoIPHelper:
|
||||
)
|
||||
|
||||
|
||||
def get_client_ip(request) -> str:
|
||||
def get_client_ip(request: Request) -> str:
|
||||
"""
|
||||
获取客户端真实 IP 地址
|
||||
支持 IPv4 和 IPv6,考虑代理、负载均衡器等情况
|
||||
@@ -66,6 +69,10 @@ def get_client_ip(request) -> str:
|
||||
return client_ip if is_valid_ip(client_ip) else "127.0.0.1"
|
||||
|
||||
|
||||
IPAddress = Annotated[str, Depends(get_client_ip)]
|
||||
GeoIPService = Annotated[GeoIPHelper, Depends(get_geoip_helper)]
|
||||
|
||||
|
||||
def is_valid_ip(ip_str: str) -> bool:
|
||||
"""
|
||||
验证 IP 地址是否有效(支持 IPv4 和 IPv6)
|
||||
|
||||
Reference in New Issue
Block a user