1
1
import os
2
2
import psycopg2
3
+ import psycopg2 .extras
3
4
4
- from fastapi import APIRouter
5
+ from fastapi import APIRouter , HTTPException
5
6
6
7
router = APIRouter ()
7
8
@@ -16,14 +17,17 @@ def get_v1_categories_count():
16
17
port = 5432 )
17
18
try :
18
19
with conn :
19
- with conn .cursor () as cur :
20
+ with conn .cursor (cursor_factory = psycopg2 . extras . RealDictCursor ) as cur :
20
21
cur .execute ('SELECT COUNT(*) AS counter FROM categories' )
21
- return cur .fetchone ()[0 ]
22
+ result = cur .fetchone ()
23
+ if result is None :
24
+ raise HTTPException (status_code = 404 )
25
+ return result
22
26
finally :
23
27
conn .close ()
24
28
25
29
@router .get ('/v1/collections/{collectionId}/categories/count' )
26
- def get_v1_collections_collection_id_categories_count ():
30
+ def get_v1_collections_collection_id_categories_count (collectionId ):
27
31
conn = psycopg2 .connect (
28
32
database = os .getenv ('DB_NAME' ),
29
33
user = os .getenv ('DB_USER' ),
@@ -32,9 +36,12 @@ def get_v1_collections_collection_id_categories_count():
32
36
port = 5432 )
33
37
try :
34
38
with conn :
35
- with conn .cursor () as cur :
36
- cur .execute ('SELECT COUNT(DISTINCT s.category_id) AS counter FROM collections_series cs JOIN series s ON s.id = cs.series_id WHERE cs.collection_id = :collectionId' )
37
- return cur .fetchone ()[0 ]
39
+ with conn .cursor (cursor_factory = psycopg2 .extras .RealDictCursor ) as cur :
40
+ cur .execute ('SELECT COUNT(DISTINCT s.category_id) AS counter FROM collections_series cs JOIN series s ON s.id = cs.series_id WHERE cs.collection_id = %(collectionId)s' , { "collectionId" : collectionId })
41
+ result = cur .fetchone ()
42
+ if result is None :
43
+ raise HTTPException (status_code = 404 )
44
+ return result
38
45
finally :
39
46
conn .close ()
40
47
@@ -47,7 +54,7 @@ def post_v1_categories():
47
54
pass
48
55
49
56
@router .get ('/v1/categories/{categoryId}' )
50
- def get_v1_categories_category_id ():
57
+ def get_v1_categories_category_id (categoryId ):
51
58
conn = psycopg2 .connect (
52
59
database = os .getenv ('DB_NAME' ),
53
60
user = os .getenv ('DB_USER' ),
@@ -56,9 +63,12 @@ def get_v1_categories_category_id():
56
63
port = 5432 )
57
64
try :
58
65
with conn :
59
- with conn .cursor () as cur :
60
- cur .execute ('SELECT id , name , name_ru , slug FROM categories WHERE id = :categoryId' )
61
- return cur .fetchone ()[0 ]
66
+ with conn .cursor (cursor_factory = psycopg2 .extras .RealDictCursor ) as cur :
67
+ cur .execute ('SELECT id , name , name_ru , slug FROM categories WHERE id = %(categoryId)s' , { "categoryId" : categoryId })
68
+ result = cur .fetchone ()
69
+ if result is None :
70
+ raise HTTPException (status_code = 404 )
71
+ return result
62
72
finally :
63
73
conn .close ()
64
74
0 commit comments