Skip to content

Commit e220aa0

Browse files
committed
refactor(python): simplify code for generating GET endpoints
Relate to #16
1 parent 8b4574e commit e220aa0

File tree

1 file changed

+10
-14
lines changed

1 file changed

+10
-14
lines changed

src/templates/routes.py.ejs

+10-14
Original file line numberDiff line numberDiff line change
@@ -201,37 +201,33 @@ def <%- pythonMethodName %>(<%- methodArgs.join(', ') %>):
201201
https://stackoverflow.com/questions/45399347/dictcursor-vs-realdictcursor
202202
-%>
203203
with conn:
204-
<% if (hasGetOne) {
205-
if (queries.length > 1) { /* we can omit cursor_factory but in this case we might get an unused import */-%>
204+
<% if (hasGetOne && queries.length > 1) { /* we can omit cursor_factory but in this case we might get an unused import */-%>
206205
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
207206
result = {}
208-
<% queries.forEach(queryInfo => {
209-
for (const [name, query] of Object.entries(queryInfo)) {
207+
<% queries.forEach(queryInfo => {
208+
for (const [name, query] of Object.entries(queryInfo)) {
210209
-%>
211210
cur.execute(<%- query.sql %><%- query.formattedParams %>)
212211
result['<%- name %>'] = cur.fetchone()[0]
213212
<% }
214-
})
213+
})
215214
-%>
216215
return result
217216
<%
218-
} else {
219-
const query = queries[0].result
217+
} else {
218+
const query = queries[0].result
220219
-%>
221220
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
222221
cur.execute(<%- query.sql %><%- query.formattedParams %>)
222+
<% if (hasGetMany) { -%>
223+
return cur.fetchall()
224+
<% } else { /* GET with a single result */ -%>
223225
result = cur.fetchone()
224226
if result is None:
225227
raise HTTPException(status_code = status.HTTP_404_NOT_FOUND)
226228
return result
227-
<% }
228-
} else {
229-
const query = queries[0].result
230-
-%>
231-
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
232-
cur.execute(<%- query.sql %><%- query.formattedParams %>)
233-
return cur.fetchall()
234229
<%
230+
}
235231
}
236232
-%>
237233
finally:

0 commit comments

Comments
 (0)