|
| 1 | +"""OpenAPI core contrib django requests module""" |
| 2 | +import re |
| 3 | + |
| 4 | +from openapi_core.validation.request.datatypes import ( |
| 5 | + RequestParameters, OpenAPIRequest, |
| 6 | +) |
| 7 | + |
| 8 | +# https://docs.djangoproject.com/en/2.2/topics/http/urls/ |
| 9 | +# |
| 10 | +# Currently unsupported are : |
| 11 | +# - nested arguments, e.g.: ^comments/(?:page-(?P<page_number>\d+)/)?$ |
| 12 | +# - unnamed regex groups, e.g.: ^articles/([0-9]{4})/$ |
| 13 | +# - multiple named parameters between a single pair of slashes |
| 14 | +# e.g.: <page_slug>-<page_id>/edit/ |
| 15 | +# |
| 16 | +# The regex matches everything, except a "/" until "<". Than only the name |
| 17 | +# is exported, after which it matches ">" and everything until a "/". |
| 18 | +PATH_PARAMETER_PATTERN = r'(?:[^\/]*?)<(?:(?:.*?:))*?(\w+)>(?:[^\/]*)' |
| 19 | + |
| 20 | + |
| 21 | +class DjangoOpenAPIRequestFactory(object): |
| 22 | + |
| 23 | + path_regex = re.compile(PATH_PARAMETER_PATTERN) |
| 24 | + |
| 25 | + @classmethod |
| 26 | + def create(cls, request): |
| 27 | + method = request.method.lower() |
| 28 | + |
| 29 | + if request.resolver_match is None: |
| 30 | + path_pattern = request.path |
| 31 | + else: |
| 32 | + route = cls.path_regex.sub( |
| 33 | + r'{\1}', request.resolver_match.route) |
| 34 | + path_pattern = '/' + route |
| 35 | + |
| 36 | + path = request.resolver_match and request.resolver_match.kwargs or {} |
| 37 | + parameters = RequestParameters( |
| 38 | + path=path, |
| 39 | + query=request.GET, |
| 40 | + header=request.headers, |
| 41 | + cookie=request.COOKIES, |
| 42 | + ) |
| 43 | + return OpenAPIRequest( |
| 44 | + host_url=request._current_scheme_host, |
| 45 | + path=request.path, |
| 46 | + method=method, |
| 47 | + path_pattern=path_pattern, |
| 48 | + parameters=parameters, |
| 49 | + body=request.body, |
| 50 | + mimetype=request.content_type, |
| 51 | + ) |
0 commit comments