router parameter in Application constructor #464
-
Application( class RouterWithPrefix(Router):
Above code is for BlackSheep V1.2.18 to add prefix to all routes,. It changes I updated to BlackSheep 2.0.4. Above cold will not work when configuration.production is True. Above cold will work when configuration.production is False. Use default_router
How to add prefix to all routes in BlackSheep 2.0.4?? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
Hi @netwang The below works fine: import os
from blacksheep import Application, Router
class RouterWithPrefix(Router):
"""Router With Prefix."""
def __init__(self, prefix: str) -> None:
super().__init__()
self.__prefix = prefix
def add(self, method: str, pattern, handler) -> None:
"""Add."""
if isinstance(pattern, str):
pattern = (self.__prefix + pattern).replace("//", "/")
else:
pattern = (self.__prefix.encode() + pattern).replace(b"//", b"/")
super().add(method, pattern, handler)
prod = os.environ.get("PROD") == "1"
app = Application(router=RouterWithPrefix(f"/example/") if prod else None)
@app.router.get("/")
def home():
return "Home!" If you define your own router, you cannot use the methods imported from BlackSheep, because they are the methods of the default router. You need to use For example, create a module in your application in # app/router.py
import os
if os.environ.get("PROD") in {"1", "true"}: # if configuration.production: ...
router = RouterWithPrefix(...)
else:
router = Router()
head = router.head
get = router.get
post = router.post
put = router.put
patch = router.patch
delete = router.delete
trace = router.trace
options = router.options
connect = router.connect
ws = router.ws
route = router.route Then use the |
Beta Was this translation helpful? Give feedback.
-
all My projects were split into 2 parts:
both application part and common library (libquad) have following code from blacksheep.server.controllers import post class xxxController(ControllerBase): Common controllers are put into the common library (libquad). That's why I can not use below solution: if os.environ.get("PROD") in {"1", "true"}: # if configuration.production: ... head = router.head I can not use app.router either. @app.router.get("/") |
Beta Was this translation helpful? Give feedback.
-
fixed async def __print_routes(application: Application) -> None:
|
Beta Was this translation helpful? Give feedback.
Hi @netwang
The below works fine: