Skip to content

Commit 316f8a3

Browse files
committed
feat: timing decorator supports sync and async functions
1 parent 4639b84 commit 316f8a3

File tree

4 files changed

+44
-2
lines changed

4 files changed

+44
-2
lines changed

Pipfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ cryptography = "*"
1414
faker = "*"
1515
fastapi = "*"
1616
pytest = "*"
17+
pytest-asyncio = "*"
1718
tortoise-orm = "*"
1819
uvicorn = "*"
1920

fastapi_esql/utils/decorator.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
from functools import wraps
23
from logging import getLogger
34
from time import perf_counter
@@ -6,11 +7,24 @@
67

78

89
def timing(func):
10+
911
@wraps(func)
10-
async def wrapper(*args, **kwargs):
12+
async def async_wrapper(*args, **kwargs):
1113
st = perf_counter()
1214
result = await func(*args, **kwargs)
1315
et = perf_counter()
1416
logger.info(f"{func.__module__}/{func.__name__} Cost {1000 * (et - st):.2f} ms")
1517
return result
16-
return wrapper
18+
19+
@wraps(func)
20+
def wrapper(*args, **kwargs):
21+
st = perf_counter()
22+
result = func(*args, **kwargs)
23+
et = perf_counter()
24+
logger.info(f"{func.__module__}/{func.__name__} Cost {1000 * (et - st):.2f} ms")
25+
return result
26+
27+
if asyncio.iscoroutinefunction(func):
28+
return async_wrapper
29+
else:
30+
return wrapper

requirements-dev.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@ cryptography
55
faker
66
fastapi
77
pytest
8+
pytest-asyncio
89
tortoise-orm
910
uvicorn

tests/test_decorator.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import pytest
2+
3+
from fastapi_esql import timing
4+
5+
6+
@timing
7+
async def afunc():
8+
"""async def afunc()"""
9+
return True
10+
11+
12+
@timing
13+
def func():
14+
"""def func()"""
15+
return False
16+
17+
18+
@pytest.mark.asyncio
19+
async def test_async_timing():
20+
print(afunc, afunc.__doc__, afunc.__name__)
21+
assert await afunc() == True
22+
23+
24+
def test_sync_timing():
25+
print(func, func.__doc__, func.__name__)
26+
assert func() == False

0 commit comments

Comments
 (0)