Skip to content

Commit

Permalink
refactor(python): simplify code for generating GET endpoints
Browse files Browse the repository at this point in the history
Relate to #16
  • Loading branch information
php-coder committed Apr 4, 2024
1 parent 8b4574e commit e220aa0
Showing 1 changed file with 10 additions and 14 deletions.
24 changes: 10 additions & 14 deletions src/templates/routes.py.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -201,37 +201,33 @@ def <%- pythonMethodName %>(<%- methodArgs.join(', ') %>):
https://stackoverflow.com/questions/45399347/dictcursor-vs-realdictcursor
-%>
with conn:
<% if (hasGetOne) {
if (queries.length > 1) { /* we can omit cursor_factory but in this case we might get an unused import */-%>
<% if (hasGetOne && queries.length > 1) { /* we can omit cursor_factory but in this case we might get an unused import */-%>
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
result = {}
<% queries.forEach(queryInfo => {
for (const [name, query] of Object.entries(queryInfo)) {
<% queries.forEach(queryInfo => {
for (const [name, query] of Object.entries(queryInfo)) {
-%>
cur.execute(<%- query.sql %><%- query.formattedParams %>)
result['<%- name %>'] = cur.fetchone()[0]
<% }
})
})
-%>
return result
<%
} else {
const query = queries[0].result
} else {
const query = queries[0].result
-%>
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
cur.execute(<%- query.sql %><%- query.formattedParams %>)
<% if (hasGetMany) { -%>
return cur.fetchall()
<% } else { /* GET with a single result */ -%>
result = cur.fetchone()
if result is None:
raise HTTPException(status_code = status.HTTP_404_NOT_FOUND)
return result
<% }
} else {
const query = queries[0].result
-%>
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
cur.execute(<%- query.sql %><%- query.formattedParams %>)
return cur.fetchall()
<%
}
}
-%>
finally:
Expand Down

0 comments on commit e220aa0

Please sign in to comment.