Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed issues with schema name collisions #5486

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 35 additions & 5 deletions rest_framework/schemas/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,21 +64,28 @@ def is_api_view(callback):
"""


class LinkNode(OrderedDict):
def __init__(self):
self.links = []
super(LinkNode, self).__init__()


def insert_into(target, keys, value):
"""
Nested dictionary insertion.

>>> example = {}
>>> insert_into(example, ['a', 'b', 'c'], 123)
>>> example
{'a': {'b': {'c': 123}}}
LinkNode({'a': LinkNode({'b': LinkNode({'c': LinkNode(links=[123])}}})))
"""
for key in keys[:-1]:
for key in keys:
if key not in target:
target[key] = {}
target[key] = LinkNode()
target = target[key]

try:
target[keys[-1]] = value
target.links.append(value)
except TypeError:
msg = INSERT_INTO_COLLISION_FMT.format(
value_url=value.url,
Expand All @@ -88,6 +95,27 @@ def insert_into(target, keys, value):
raise ValueError(msg)


def get_unique_key(obj, base_key):
i = 0
while True:
key = '{}_{}'.format(base_key, i)
if key not in obj:
return key
i += 1


def distribute_links(obj, parent=None, parent_key='root'):
if parent is None:
parent = obj

for link in obj.links:
key = get_unique_key(parent, parent_key)
parent[key] = link

for key, value in obj.items():
distribute_links(value, obj, key)


def is_custom_action(action):
return action not in set([
'retrieve', 'list', 'create', 'update', 'partial_update', 'destroy'
Expand Down Expand Up @@ -255,6 +283,7 @@ def get_schema(self, request=None, public=False):
if not url and request is not None:
url = request.build_absolute_uri()

distribute_links(links)
return coreapi.Document(
title=self.title, description=self.description,
url=url, content=links
Expand All @@ -265,7 +294,7 @@ def get_links(self, request=None):
Return a dictionary containing all the links that should be
included in the API schema.
"""
links = OrderedDict()
links = LinkNode()

# Generate (path, method, view) given (path, method, callback).
paths = []
Expand All @@ -288,6 +317,7 @@ def get_links(self, request=None):
subpath = path[len(prefix):]
keys = self.get_keys(subpath, method, view)
insert_into(links, keys, link)

return links

# Methods used when we generate a view instance from the raw callback...
Expand Down
Loading