Skip to content

Commit 4caebf2

Browse files
committed
feat(python): implement generation of POST endpoints
Part of #16
1 parent e220aa0 commit 4caebf2

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed

examples/python/fastapi/postgres/routes.py

+29-2
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,35 @@ def get_list_v1_categories(limit, conn=Depends(db_connection)):
9090

9191

9292
@router.post('/v1/categories', status_code = status.HTTP_204_NO_CONTENT)
93-
def post_v1_categories(payload: CreateCategoryDto):
94-
pass
93+
94+
def post_v1_categories(payload: CreateCategoryDto, conn=Depends(db_connection)):
95+
try:
96+
with conn:
97+
with conn.cursor() as cur:
98+
cur.execute(
99+
"""
100+
INSERT
101+
INTO categories
102+
( name
103+
, name_ru
104+
, slug
105+
, created_at
106+
, created_by
107+
, updated_at
108+
, updated_by
109+
)
110+
VALUES
111+
( %(name)s
112+
, %(name_ru)s
113+
, %(slug)s
114+
, NOW()
115+
, %(user_id)s
116+
, NOW()
117+
, %(user_id)s
118+
)
119+
""", {"name": payload.name, "name_ru": payload.name_ru, "slug": payload.slug, "user_id": payload.user_id, "user_id": payload.user_id})
120+
finally:
121+
conn.close()
95122

96123

97124
@router.get('/v1/categories/{categoryId}')

src/templates/routes.py.ejs

+16-2
Original file line numberDiff line numberDiff line change
@@ -239,11 +239,25 @@ def <%- pythonMethodName %>(<%- methodArgs.join(', ') %>):
239239
// LATER: do we really need signature and cache?
240240
const cacheKey = dto ? dto.signature : null;
241241
const model = dtoInCache(dto) ? dtoCache[cacheKey] : dto.name;
242+
243+
const sql = convertToPsycopgNamedArguments(formatQueryForPython(method.query, 20))
244+
const params = extractParamsFromQuery(method.query);
245+
const formattedParams = params.length > 0
246+
// [ "p.categoryId" ] => [ '"categoryId": payload.categoryId' ]
247+
? ', {' + params.map(param => param.substring(2)).map(param => `"${param}": payload.${param}`).join(', ') + '}'
248+
: ''
249+
242250
%>
243251
244252
@router.post('<%- path %>', status_code = status.HTTP_204_NO_CONTENT)
245-
def <%- pythonMethodName %>(payload: <%- model %>):
246-
pass
253+
<%# LATER: deal with methodArgs %>
254+
def <%- pythonMethodName %>(payload: <%- model %>, conn=Depends(db_connection)):
255+
try:
256+
with conn:
257+
with conn.cursor() as cur:
258+
cur.execute(<%- sql %><%- formattedParams %>)
259+
finally:
260+
conn.close()
247261
<%
248262
249263
}

0 commit comments

Comments
 (0)