Skip to content

Commit b35c591

Browse files
committed
[#19] fix: Trailing slash in APIBlueprint
1 parent 82f9ccb commit b35c591

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

flask_openapi3/api_blueprint.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,11 @@ def _do_decorator(
125125
# parse response
126126
get_responses(combine_responses, extra_responses, self.components_schemas, operation)
127127
uri = get_openapi_path(rule)
128+
trail_slash = uri.endswith('/')
128129
# merge url_prefix and uri
129130
uri = self.url_prefix.rstrip("/") + "/" + uri.lstrip("/") if self.url_prefix else uri
131+
if not trail_slash:
132+
uri = uri.rstrip('/')
130133
# parse method
131134
parse_method(uri, method, self.paths, operation)
132135
return header, cookie, path, query, form, body, combine_responses

tests/test_trail_slash.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# -*- coding: utf-8 -*-
2+
# @Author : llc
3+
# @Time : 2022/5/5 13:28
4+
5+
import pytest
6+
7+
from flask_openapi3 import Info
8+
from flask_openapi3 import OpenAPI, APIBlueprint
9+
10+
info = Info(title='book API', version='1.0.0')
11+
12+
app = OpenAPI(__name__, info=info)
13+
app.config["TESTING"] = True
14+
15+
api1 = APIBlueprint('book1', __name__, url_prefix='/api/v1/book1')
16+
api2 = APIBlueprint('book2', __name__, url_prefix='/api/v1/book2')
17+
18+
19+
@pytest.fixture
20+
def client():
21+
client = app.test_client()
22+
23+
return client
24+
25+
26+
@api1.get('/')
27+
def get_book():
28+
return 'with slash'
29+
30+
31+
@api2.get('')
32+
def get_book2():
33+
return 'without slash'
34+
35+
36+
app.register_api(api1)
37+
app.register_api(api2)
38+
39+
40+
def test_with_slash1(client):
41+
resp = client.get("/api/v1/book1/")
42+
assert resp.status_code == 200
43+
44+
45+
def test_with_slash2(client):
46+
resp = client.get("/api/v1/book1")
47+
assert resp.status_code == 308
48+
49+
50+
def test_without_slash1(client):
51+
resp = client.get("/api/v1/book2/")
52+
assert resp.status_code == 404
53+
54+
55+
def test_without_slash2(client):
56+
resp = client.get("/api/v1/book2")
57+
assert resp.status_code == 200
58+
59+
60+
def test_openapi(client):
61+
resp = client.get("/openapi/openapi.json")
62+
_json = resp.json
63+
assert _json['paths'].get('/api/v1/book1/') is not None
64+
assert _json['paths'].get('/api/v1/book2') is not None

0 commit comments

Comments
 (0)