Add pre-registry

This commit is contained in:
Adam Hopkins 2021-12-15 01:07:42 +02:00
parent f282865362
commit a0a3840094
No known key found for this signature in database
GPG Key ID: 9F85EE6C807303FB
2 changed files with 31 additions and 1 deletions

View File

@ -50,7 +50,7 @@ from sanic_routing.exceptions import ( # type: ignore
)
from sanic_routing.route import Route # type: ignore
from sanic import reloader_helpers
from sanic import blueprint_group, reloader_helpers
from sanic.application.logo import get_logo
from sanic.application.motd import MOTD
from sanic.application.state import ApplicationState, Mode
@ -536,6 +536,12 @@ class Sanic(BaseSanic, metaclass=TouchUpMeta):
blueprint.strict_slashes = self.strict_slashes
blueprint.register(self, options)
def _register_lazy_blueprints(self):
for name, reg_info in Blueprint.__pre_registry__.items():
blueprint = reg_info.pop("bp")
if name == self.name and blueprint.name not in self.blueprints:
self.blueprint(blueprint, **reg_info)
def url_for(self, view_name: str, **kwargs):
"""Build a URL based on a view name and the values provided.
@ -1697,6 +1703,7 @@ class Sanic(BaseSanic, metaclass=TouchUpMeta):
async def _startup(self):
self._future_registry.clear()
self._register_lazy_blueprints()
self.signalize()
self.finalize()
ErrorHandler.finalize(

View File

@ -107,6 +107,7 @@ class Blueprint(BaseSanic):
"version_prefix",
"websocket_routes",
)
__pre_registry__: Dict[str, Any] = {}
def __init__(
self,
@ -461,3 +462,25 @@ class Blueprint(BaseSanic):
):
for app in apps:
app._future_registry.update(set((bp, item) for item in futures))
def pre_register(
self,
name: str = None,
url_prefix: Optional[str] = None,
host: Optional[Union[List[str], str]] = None,
version: Optional[Union[int, str, float]] = None,
strict_slashes: Optional[bool] = None,
version_prefix: Union[str, Default] = _default,
) -> None:
self.__class__.__pre_registry__[name] = {
k: v
for k, v in {
"bp": self,
"url_prefix": url_prefix,
"host": host,
"version": version,
"strict_slashes": strict_slashes,
"version_prefix": version_prefix,
}.items()
if v is not None and v is not _default
}