Skip to content

Commit 595c190

Browse files
committed
feat(python): include user defined routes from *_routes.py` files
In order to include custom routes: - create a file <name>_routes.py - implement endpoints and ensure that the file contains FastAPI's APIRouter named "router" Part of #27
1 parent c8d0c39 commit 595c190

File tree

4 files changed

+41
-0
lines changed

4 files changed

+41
-0
lines changed

examples/python/app.py

+4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
from fastapi import FastAPI
22
from routes import router
33

4+
from custom_routes import router as custom_route
5+
46
app = FastAPI()
57

68
app.include_router(router)
9+
10+
app.include_router(custom_route)

examples/python/custom_routes.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from fastapi import APIRouter
2+
3+
router = APIRouter()
4+
5+
6+
@router.get('/v1/hello')
7+
def greetings():
8+
return {"hello": "world!"}

src/cli.js

+10
Original file line numberDiff line numberDiff line change
@@ -82,15 +82,25 @@ const lang2extension = (lang) => {
8282
}
8383
}
8484

85+
const findFileNamesEndWith = (dir, postfix) => {
86+
return fs.readdirSync(dir).filter(name => name.endsWith(postfix))
87+
}
88+
8589
const createApp = async (destDir, lang) => {
8690
const ext = lang2extension(lang)
8791
const fileName = `app.${ext}`
8892
console.log('Generate', fileName);
8993
const resultFile = path.join(destDir, fileName);
94+
const customRouters = findFileNamesEndWith(destDir, `_routes.${ext}`)
95+
if (customRouters.length > 0) {
96+
customRouters.forEach(filename => console.log(`Include a custom router from ${filename}`))
97+
}
9098

9199
const resultedCode = await ejs.renderFile(
92100
`${__dirname}/templates/${fileName}.ejs`,
93101
{
102+
// @todo #27 Document usage of user defined routes
103+
'customRouteFilenames': customRouters
94104
}
95105
)
96106

src/templates/app.py.ejs

+19
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,25 @@
1+
<%
2+
3+
// "custom_routes.py" => "custom_route"
4+
function fileName2routerName(filename) {
5+
return filename.replace(/_routes\.py$/, '_route')
6+
}
7+
8+
// "custom_routes.py" => "custom_routes"
9+
function removeExtension(filename) {
10+
return filename.replace(/\.py$/, '')
11+
}
12+
13+
-%>
114
from fastapi import FastAPI
215
from routes import router
16+
<% customRouteFilenames.forEach(filename => { %>
17+
from <%= removeExtension(filename) %> import router as <%= fileName2routerName(filename) %>
18+
<% }) -%>
319

420
app = FastAPI()
521

622
app.include_router(router)
23+
<% customRouteFilenames.forEach(filename => { %>
24+
app.include_router(<%= fileName2routerName(filename) %>)
25+
<% }) -%>

0 commit comments

Comments
 (0)