From d6037fc0986855c9b0f189a13a651ad7f18dee63 Mon Sep 17 00:00:00 2001 From: Zhiwei Liang Date: Wed, 7 Jul 2021 01:01:05 -0700 Subject: [PATCH] Initial version of Blueprint.copy, with a test case. --- sanic/blueprints.py | 18 ++++++++++++++++++ tests/test_blueprint_copy.py | 24 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 tests/test_blueprint_copy.py diff --git a/sanic/blueprints.py b/sanic/blueprints.py index 1fa24e88..3afe9355 100644 --- a/sanic/blueprints.py +++ b/sanic/blueprints.py @@ -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, diff --git a/tests/test_blueprint_copy.py b/tests/test_blueprint_copy.py new file mode 100644 index 00000000..022c1160 --- /dev/null +++ b/tests/test_blueprint_copy.py @@ -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