2
2
import psycopg2
3
3
import psycopg2 .extras
4
4
5
- from fastapi import APIRouter , HTTPException
5
+ from fastapi import APIRouter , Depends , HTTPException
6
6
7
7
router = APIRouter ()
8
8
9
-
10
- @router .get ('/v1/categories/count' )
11
- def get_v1_categories_count ():
12
- conn = psycopg2 .connect (
9
+ async def db_connection ():
10
+ return psycopg2 .connect (
13
11
database = os .getenv ('DB_NAME' ),
14
12
user = os .getenv ('DB_USER' ),
15
13
password = os .getenv ('DB_PASSWORD' ),
16
14
host = os .getenv ('DB_HOST' , 'localhost' ),
17
15
port = 5432 )
16
+
17
+
18
+ @router .get ('/v1/categories/count' )
19
+ def get_v1_categories_count (conn = Depends (db_connection )):
18
20
try :
19
21
with conn :
20
22
with conn .cursor (cursor_factory = psycopg2 .extras .RealDictCursor ) as cur :
@@ -27,13 +29,7 @@ def get_v1_categories_count():
27
29
conn .close ()
28
30
29
31
@router .get ('/v1/categories/stat' )
30
- def get_v1_categories_stat ():
31
- conn = psycopg2 .connect (
32
- database = os .getenv ('DB_NAME' ),
33
- user = os .getenv ('DB_USER' ),
34
- password = os .getenv ('DB_PASSWORD' ),
35
- host = os .getenv ('DB_HOST' , 'localhost' ),
36
- port = 5432 )
32
+ def get_v1_categories_stat (conn = Depends (db_connection )):
37
33
try :
38
34
with conn :
39
35
with conn .cursor (cursor_factory = psycopg2 .extras .DictCursor ) as cur :
@@ -51,13 +47,7 @@ def get_v1_categories_stat():
51
47
conn .close ()
52
48
53
49
@router .get ('/v1/collections/{collectionId}/categories/count' )
54
- def get_v1_collections_collection_id_categories_count (collectionId ):
55
- conn = psycopg2 .connect (
56
- database = os .getenv ('DB_NAME' ),
57
- user = os .getenv ('DB_USER' ),
58
- password = os .getenv ('DB_PASSWORD' ),
59
- host = os .getenv ('DB_HOST' , 'localhost' ),
60
- port = 5432 )
50
+ def get_v1_collections_collection_id_categories_count (collectionId , conn = Depends (db_connection )):
61
51
try :
62
52
with conn :
63
53
with conn .cursor (cursor_factory = psycopg2 .extras .RealDictCursor ) as cur :
@@ -70,21 +60,15 @@ def get_v1_collections_collection_id_categories_count(collectionId):
70
60
conn .close ()
71
61
72
62
@router .get ('/v1/categories' )
73
- def get_list_v1_categories ():
63
+ def get_list_v1_categories (conn = Depends ( db_connection ) ):
74
64
pass
75
65
76
66
@router .post ('/v1/categories' )
77
67
def post_v1_categories ():
78
68
pass
79
69
80
70
@router .get ('/v1/categories/{categoryId}' )
81
- def get_v1_categories_category_id (categoryId ):
82
- conn = psycopg2 .connect (
83
- database = os .getenv ('DB_NAME' ),
84
- user = os .getenv ('DB_USER' ),
85
- password = os .getenv ('DB_PASSWORD' ),
86
- host = os .getenv ('DB_HOST' , 'localhost' ),
87
- port = 5432 )
71
+ def get_v1_categories_category_id (categoryId , conn = Depends (db_connection )):
88
72
try :
89
73
with conn :
90
74
with conn .cursor (cursor_factory = psycopg2 .extras .RealDictCursor ) as cur :
0 commit comments