From bd6dbd9090049d149bdab1826b6b0ce9d122b92c Mon Sep 17 00:00:00 2001 From: jacob Date: Sat, 29 Sep 2018 18:23:16 +0800 Subject: [PATCH] Fix TypeError when use Blueprint.group() to group blueprint with default url_prefix, Use os.path.normpath to avoid invalid url_prefix like api//v1 --- sanic/blueprints.py | 4 ++++ tests/test_blueprints.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/sanic/blueprints.py b/sanic/blueprints.py index 084013e1..93d38665 100644 --- a/sanic/blueprints.py +++ b/sanic/blueprints.py @@ -1,3 +1,4 @@ +import os from collections import defaultdict, namedtuple from sanic.constants import HTTP_METHODS @@ -54,7 +55,10 @@ class Blueprint: yield i bps = [] for bp in chain(blueprints): + if bp.url_prefix is None: + bp.url_prefix = '' bp.url_prefix = url_prefix + bp.url_prefix + bp.url_prefix = os.path.normpath(bp.url_prefix) bps.append(bp) return bps diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py index 4b821e91..214c2f9a 100644 --- a/tests/test_blueprints.py +++ b/tests/test_blueprints.py @@ -499,3 +499,40 @@ def test_bp_group(app): request, response = app.test_client.get('/mid/deep1/bottom') assert response.text == 'D1B_OK' + + +def test_bp_group_with_default_url_prefix(app): + + from sanic.response import json + bp_resources = Blueprint('bp_resources') + @bp_resources.get('/') + def list_resources_handler(request): + resource = {} + return json([resource]) + + bp_resource = Blueprint('bp_resource', url_prefix='/') + @bp_resource.get('/') + def get_resource_hander(request, resource_id): + resource = {'resource_id': resource_id} + return json(resource) + + bp_resources_group = Blueprint.group(bp_resources, bp_resource, url_prefix='/resources/') + bp_api_v1 = Blueprint('bp_api_v1', url_prefix='/') + @bp_api_v1.get('/info') + def api_v1_info(request): + return text('api_version: v1') + + bp_api_v1_group = Blueprint.group(bp_api_v1, bp_resources_group, url_prefix='/v1') + bp_api_group = Blueprint.group(bp_api_v1_group, url_prefix='/api') + app.blueprint(bp_api_group) + + request, response = app.test_client.get('/api/v1/info') + assert response.text == 'api_version: v1' + + request, response = app.test_client.get('/api/v1/resources') + assert response.json == [{}] + + from uuid import uuid4 + resource_id = str(uuid4()) + request, response = app.test_client.get('/api/v1/resources/{0}'.format(resource_id)) + assert response.json == {'resource_id': resource_id}