Allow application creation from Blueprint at startup

This commit is contained in:
Adam Hopkins 2021-12-15 09:36:40 +02:00
parent 266af1e279
commit c8fa52e2d2
No known key found for this signature in database
GPG Key ID: 9F85EE6C807303FB
3 changed files with 22 additions and 2 deletions

View File

@ -547,6 +547,9 @@ class Sanic(BaseSanic, metaclass=TouchUpMeta):
"pre-registrations must use an application name."
)
if self.name in registry and _default in registry:
registry[_default].extend(registry.pop(self.name))
registry = {
self.name if k is _default else k: v
for k, v in registry.items()
@ -1712,7 +1715,8 @@ class Sanic(BaseSanic, metaclass=TouchUpMeta):
version_prefix: str = "/v",
) -> Blueprint:
if not name:
name = f"bp{len(Blueprint.__pre_registry__)}"
flat = [1 for x in Blueprint.__pre_registry__.values() for _ in x]
name = f"bp{len(flat)}"
bp = Blueprint(
name=name,
url_prefix=url_prefix,

View File

@ -472,6 +472,9 @@ class Blueprint(BaseSanic):
strict_slashes: Optional[bool] = None,
version_prefix: Union[str, Default] = _default,
) -> None:
if not hasattr(self.ctx, "_prereg"):
self.ctx._prereg = []
self.ctx._prereg.append(name)
self.__class__.__pre_registry__[name].append(
{
k: v

View File

@ -10,7 +10,9 @@ from typing import Any, List, Union
from sanic.app import Sanic
from sanic.application.logo import get_logo
from sanic.blueprints import Blueprint
from sanic.cli.arguments import Group
from sanic.helpers import _default
from sanic.log import error_logger
from sanic.simple import create_simple_server
@ -20,6 +22,7 @@ class SanicArgumentParser(ArgumentParser):
class SanicCLI:
DEFAULT_APP_NAME = "SANIC"
DESCRIPTION = indent(
f"""
{get_logo(True)}
@ -131,7 +134,17 @@ Or, a path to a directory to run as a simple HTTP server:
app_type_name = type(app).__name__
if not isinstance(app, Sanic):
if isinstance(app, Blueprint):
bp = app
name = (
bp.ctx._prereg[0]
if hasattr(bp.ctx, "_prereg")
else _default
)
if name is _default:
name = self.DEFAULT_APP_NAME
app = Sanic(name)
elif not isinstance(app, Sanic):
raise ValueError(
f"Module is not a Sanic app, it is a {app_type_name}\n"
f" Perhaps you meant {self.args.module}.app?"