Skip to content

Commit 84be6f7

Browse files
committed
added utils aggregate to simplify code design
1 parent c04f6cf commit 84be6f7

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

app/utils/utils.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import logging
2+
3+
from aiohttp import ClientSession
4+
from dateutil.parser import parse
5+
6+
class Utils:
7+
# Singleton aiohttp.ClientSession instance.
8+
CLIENT_SESSION: ClientSession
9+
10+
LOGGER = logging.getLogger(__name__)
11+
12+
async def setup_client_session():
13+
"""Set up the application-global aiohttp.ClientSession instance.
14+
15+
aiohttp recommends that only one ClientSession exist for the lifetime of an application.
16+
See: https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request
17+
18+
"""
19+
global CLIENT_SESSION # pylint: disable=global-statement
20+
LOGGER.info("Setting up global aiohttp.ClientSession.")
21+
CLIENT_SESSION = ClientSession()
22+
23+
async def teardown_client_session():
24+
"""Close the application-global aiohttp.ClientSession.
25+
"""
26+
global CLIENT_SESSION # pylint: disable=global-statement
27+
LOGGER.info("Closing global aiohttp.ClientSession.")
28+
await CLIENT_SESSION.close()
29+
30+
31+
def is_date(string, fuzzy=False):
32+
"""
33+
Return whether the string can be interpreted as a date.
34+
- https://stackoverflow.com/a/25341965/7120095
35+
36+
:param string: str, string to check for date
37+
:param fuzzy: bool, ignore unknown tokens in string if True
38+
"""
39+
40+
try:
41+
parse(string, fuzzy=fuzzy)
42+
return True
43+
except ValueError:
44+
return False

0 commit comments

Comments
 (0)