Initial version of Blueprint.copy, with a test case.

This commit is contained in:
Zhiwei Liang 2021-07-07 01:01:05 -07:00
parent 53da4dd091
commit d6037fc098
2 changed files with 42 additions and 0 deletions

View File

@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
from collections import defaultdict
from copy import deepcopy
from types import SimpleNamespace
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Union
@ -144,6 +145,23 @@ class Blueprint(BaseSanic):
kwargs["apply"] = False
return super().signal(event, *args, **kwargs)
def copy(
self,
name: str,
url_prefix: str = "",
version: Optional[Union[int, str, float]] = None,
strict_slashes: Optional[bool] = None,
version_prefix: str = "/v",
):
new_bp = deepcopy(self)
new_bp.name = name
new_bp.url_prefix = url_prefix
new_bp.version = version
new_bp.strict_slashes = strict_slashes
new_bp.version_prefix = version_prefix
return new_bp
@staticmethod
def group(
*blueprints,

View File

@ -0,0 +1,24 @@
from copy import deepcopy
from sanic import Blueprint, Sanic, blueprints, response
from sanic.response import text
def test_bp_copy(app: Sanic):
bp1 = Blueprint("test1", version=1)
@bp1.route("/page")
def handle_request(request):
return text("Hello world!")
bp2 = bp1.copy(name="test2", version=2)
assert id(bp1) != id(bp2)
app.blueprint(bp1)
app.blueprint(bp2)
_, response = app.test_client.get("/v1/page")
assert "Hello world!" in response.text
_, response = app.test_client.get("/v2/page")
assert "Hello world!" in response.text