Browse Source

Add force_init argument to ReferenceResolver constructor

Closes #325
tags/1.14.0
Cristi Vijdea 10 months ago
parent
commit
e108ddbb48
3 changed files with 15 additions and 6 deletions
  1. 1
    1
      src/drf_yasg/generators.py
  2. 12
    3
      src/drf_yasg/openapi.py
  3. 2
    2
      tests/test_referenceresolver.py

+ 1
- 1
src/drf_yasg/generators.py View File

@@ -238,7 +238,7 @@ class OpenAPISchemaGenerator(object):
:rtype: openapi.Swagger
"""
endpoints = self.get_endpoints(request)
components = ReferenceResolver(openapi.SCHEMA_DEFINITIONS)
components = ReferenceResolver(openapi.SCHEMA_DEFINITIONS, force_init=True)
self.consumes = get_consumes(api_settings.DEFAULT_PARSER_CLASSES)
self.produces = get_produces(api_settings.DEFAULT_RENDERER_CLASSES)
paths, prefix = self.get_paths(endpoints, components, request, public)

+ 12
- 3
src/drf_yasg/openapi.py View File

@@ -617,16 +617,25 @@ class ReferenceResolver(object):
::

> components = ReferenceResolver('definitions', 'parameters')
> definitions = ReferenceResolver.with_scope('definitions')
> definitions = components.with_scope('definitions')
> definitions.set('Article', Schema(...))
> print(components)
{'definitions': OrderedDict([('Article', Schema(...)]), 'parameters': OrderedDict()}
"""

def __init__(self, *scopes):
def __init__(self, *scopes, force_init=False):
"""
:param str scopes: an enumeration of the valid scopes this resolver will contain
"""
if not force_init:
raise AssertionError(
"Creating an instance of ReferenceResolver almost certainly won't do what you want it to do.\n"
"See https://github.com/axnsan12/drf-yasg/issues/211, "
"https://github.com/axnsan12/drf-yasg/issues/271, "
"https://github.com/axnsan12/drf-yasg/issues/325.\n"
"Pass `force_init=True` to override this."
)

self._objects = OrderedDict()
self._force_scope = None
for scope in scopes:
@@ -641,7 +650,7 @@ class ReferenceResolver(object):
:rtype: .ReferenceResolver
"""
assert scope in self.scopes, "unknown scope %s" % scope
ret = ReferenceResolver()
ret = ReferenceResolver(force_init=True)
ret._objects = self._objects
ret._force_scope = scope
return ret

+ 2
- 2
tests/test_referenceresolver.py View File

@@ -5,7 +5,7 @@ from drf_yasg.openapi import ReferenceResolver

def test_basic():
scopes = ['s1', 's2']
rr = ReferenceResolver(*scopes)
rr = ReferenceResolver(*scopes, force_init=True)
assert scopes == rr.scopes == list(rr.keys()) == list(rr)
rr.set('o1', 1, scope='s1')
assert rr.has('o1', scope='s1')
@@ -25,7 +25,7 @@ def test_basic():

def test_scoped():
scopes = ['s1', 's2']
rr = ReferenceResolver(*scopes)
rr = ReferenceResolver(*scopes, force_init=True)
r1 = rr.with_scope('s1')
r2 = rr.with_scope('s2')
with pytest.raises(AssertionError):

Loading…
Cancel
Save