Skip to content

Commit d38b94f

Browse files
tilteccarltongibson
authored andcommitted
Fix URL pattern parsing in schema generation (#5689)
* Fix url parsing in schema generation - Call `str(pattern)` to get non-escaped route - Strip converters from path to comply with uritemplate format. Background: #5675 (comment) Fixes #5675
1 parent ea0b3b3 commit d38b94f

File tree

3 files changed

+72
-3
lines changed

3 files changed

+72
-3
lines changed

rest_framework/compat.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
def get_regex_pattern(urlpattern):
3333
if hasattr(urlpattern, 'pattern'):
3434
# Django 2.0
35-
return urlpattern.pattern.regex.pattern
35+
return str(urlpattern.pattern)
3636
else:
3737
# Django < 2.0
3838
return urlpattern.regex.pattern
@@ -255,6 +255,14 @@ def md_filter_add_syntax_highlight(md):
255255
except ImportError:
256256
InvalidTimeError = Exception
257257

258+
# Django 1.x url routing syntax. Remove when dropping Django 1.11 support.
259+
try:
260+
from django.urls import include, path, re_path # noqa
261+
except ImportError:
262+
from django.conf.urls import include, url # noqa
263+
path = None
264+
re_path = url
265+
258266

259267
# `separators` argument to `json.dumps()` differs between 2.x and 3.x
260268
# See: http://bugs.python.org/issue22767

rest_framework/schemas/generators.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
See schemas.__init__.py for package overview.
55
"""
6+
import re
67
import warnings
78
from collections import Counter, OrderedDict
89
from importlib import import_module
@@ -135,6 +136,11 @@ def endpoint_ordering(endpoint):
135136
return (path, method_priority)
136137

137138

139+
_PATH_PARAMETER_COMPONENT_RE = re.compile(
140+
r'<(?:(?P<converter>[^>:]+):)?(?P<parameter>\w+)>'
141+
)
142+
143+
138144
class EndpointEnumerator(object):
139145
"""
140146
A class to determine the available API endpoints that a project exposes.
@@ -189,7 +195,9 @@ def get_path_from_regex(self, path_regex):
189195
Given a URL conf regex, return a URI template string.
190196
"""
191197
path = simplify_regex(path_regex)
192-
path = path.replace('<', '{').replace('>', '}')
198+
199+
# Strip Django 2.0 convertors as they are incompatible with uritemplate format
200+
path = re.sub(_PATH_PARAMETER_COMPONENT_RE, r'{\g<parameter>}', path)
193201
return path
194202

195203
def should_include_endpoint(self, path, callback):

tests/test_schemas.py

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from rest_framework import (
1010
filters, generics, pagination, permissions, serializers
1111
)
12-
from rest_framework.compat import coreapi, coreschema, get_regex_pattern
12+
from rest_framework.compat import coreapi, coreschema, get_regex_pattern, path
1313
from rest_framework.decorators import (
1414
api_view, detail_route, list_route, schema
1515
)
@@ -361,6 +361,59 @@ def test_schema_for_regular_views(self):
361361
assert schema == expected
362362

363363

364+
@unittest.skipUnless(coreapi, 'coreapi is not installed')
365+
@unittest.skipUnless(path, 'needs Django 2')
366+
class TestSchemaGeneratorDjango2(TestCase):
367+
def setUp(self):
368+
self.patterns = [
369+
path('example/', ExampleListView.as_view()),
370+
path('example/<int:pk>/', ExampleDetailView.as_view()),
371+
path('example/<int:pk>/sub/', ExampleDetailView.as_view()),
372+
]
373+
374+
def test_schema_for_regular_views(self):
375+
"""
376+
Ensure that schema generation works for APIView classes.
377+
"""
378+
generator = SchemaGenerator(title='Example API', patterns=self.patterns)
379+
schema = generator.get_schema()
380+
expected = coreapi.Document(
381+
url='',
382+
title='Example API',
383+
content={
384+
'example': {
385+
'create': coreapi.Link(
386+
url='/example/',
387+
action='post',
388+
fields=[]
389+
),
390+
'list': coreapi.Link(
391+
url='/example/',
392+
action='get',
393+
fields=[]
394+
),
395+
'read': coreapi.Link(
396+
url='/example/{id}/',
397+
action='get',
398+
fields=[
399+
coreapi.Field('id', required=True, location='path', schema=coreschema.String())
400+
]
401+
),
402+
'sub': {
403+
'list': coreapi.Link(
404+
url='/example/{id}/sub/',
405+
action='get',
406+
fields=[
407+
coreapi.Field('id', required=True, location='path', schema=coreschema.String())
408+
]
409+
)
410+
}
411+
}
412+
}
413+
)
414+
assert schema == expected
415+
416+
364417
@unittest.skipUnless(coreapi, 'coreapi is not installed')
365418
class TestSchemaGeneratorNotAtRoot(TestCase):
366419
def setUp(self):

0 commit comments

Comments
 (0)