mirror of
https://github.com/fastapi-practices/fastapi-best-architecture.git
synced 2026-09-21 13:12:24 +00:00
Refactor the data rule to scope rule (#596)
* WIP * update codes * update codes * update filter_data_permission * Fix schema * Fix issues
This commit is contained in:
@@ -1,11 +1,17 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
import asyncio
|
||||
import functools
|
||||
import time
|
||||
|
||||
from math import ceil
|
||||
from typing import Any, Callable
|
||||
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from fastapi.routing import APIRoute
|
||||
|
||||
from backend.common.exception import errors
|
||||
from backend.common.log import log
|
||||
|
||||
|
||||
def ensure_unique_route_names(app: FastAPI) -> None:
|
||||
@@ -34,3 +40,34 @@ async def http_limit_callback(request: Request, response: Response, expire: int)
|
||||
"""
|
||||
expires = ceil(expire / 1000)
|
||||
raise errors.HTTPError(code=429, msg='请求过于频繁,请稍后重试', headers={'Retry-After': str(expires)})
|
||||
|
||||
|
||||
def timer(func) -> Callable:
|
||||
"""函数耗时计时装饰器"""
|
||||
|
||||
@functools.wraps(func)
|
||||
async def async_wrapper(*args, **kwargs) -> Any:
|
||||
start_time = time.perf_counter()
|
||||
result = await func(*args, **kwargs)
|
||||
elapsed_seconds = time.perf_counter() - start_time
|
||||
_log_time(func, elapsed_seconds)
|
||||
return result
|
||||
|
||||
@functools.wraps(func)
|
||||
def sync_wrapper(*args, **kwargs) -> Any:
|
||||
start_time = time.perf_counter()
|
||||
result = func(*args, **kwargs)
|
||||
elapsed_seconds = time.perf_counter() - start_time
|
||||
_log_time(func, elapsed_seconds)
|
||||
return result
|
||||
|
||||
def _log_time(func, elapsed: float):
|
||||
# 智能选择单位(秒、毫秒、微秒、纳秒)
|
||||
if elapsed >= 1:
|
||||
unit, factor = 's', 1
|
||||
else:
|
||||
unit, factor = 'ms', 1e3
|
||||
|
||||
log.info(f'{func.__module__}.{func.__name__} | {elapsed * factor:.3f} {unit}')
|
||||
|
||||
return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper
|
||||
|
||||
Reference in New Issue
Block a user