Skip to content

Commit

Permalink
Improvement solution for issue 311
Browse files Browse the repository at this point in the history
I've wrote a better solution replacing the references '$ref' with the recursive method __replace_ref
  • Loading branch information
isaacfi committed Jul 10, 2019
1 parent 3cb03f4 commit f77ea0a
Showing 1 changed file with 39 additions and 12 deletions.
51 changes: 39 additions & 12 deletions flasgger/utils.py
Expand Up @@ -6,6 +6,7 @@
import inspect
import os
import re
import sys
import jsonschema
import yaml
from six import string_types, text_type
Expand Down Expand Up @@ -251,6 +252,36 @@ def wrapper(*args, **kwargs):
return decorator


def __replace_ref(schema: dict, relative_path: str):
absolute_path = os.path.dirname(sys.argv[0])
new_value = {}
for key, value in schema.items():
print('key:', key)
print('value:', value)
if isinstance(value, dict):
new_value[key] = __replace_ref(value, relative_path)
elif key == '$ref':
if len(value) > 0 and value[0] == '/':
file_ref_path = absolute_path+value
else:
file_ref_path = relative_path + '/'+value
relative_path = os.path.dirname(file_ref_path)
with open(file_ref_path) as file:
file_content = file.read()
comment_index = file_content.rfind('---')
if comment_index > 0:
comment_index = comment_index + 3
else:
comment_index = 0
content = yaml.safe_load((file_content[comment_index:]))
new_value = content
if isinstance(content, dict):
new_value = __replace_ref(content, relative_path)
else:
new_value[key] = value
return new_value


def validate(
data=None, schema_id=None, filepath=None, root=None, definition=None,
specs=None, validation_function=None, validation_error_handler=None):
Expand Down Expand Up @@ -359,18 +390,12 @@ def validate(
if validation_function is None:
validation_function = jsonschema.validate

if '$ref' in main_def:
file_ref_path = os.path.dirname(sys.argv[0])+main_def['$ref']
with open(file_ref_path) as file:
file_content = file.read()
comment_index = file_content.rfind('---')
if comment_index > 0:
comment_index = comment_index + 3
else:
comment_index = 0
main_def = yaml.safe_load(
(file_content[comment_index:]).replace('\n', '\n '))
main_def['definitions'] = definitions
absolute_path = os.path.dirname(sys.argv[0])
if filepath is None:
relative_path = absolute_path
else:
relative_path = os.path.dirname(filepath)
main_def = __replace_ref(main_def, relative_path)

try:
validation_function(data, main_def)
Expand Down Expand Up @@ -821,6 +846,7 @@ class LazyString(StringLike):
A lazy string *without* caching. The resulting string is regenerated for
every request.
"""

def __init__(self, func):
"""
Creates a `LazyString` object using `func` as the delayed closure.
Expand All @@ -839,6 +865,7 @@ class CachedLazyString(LazyString):
"""
A lazy string with caching.
"""

def __init__(self, func):
"""
Uses `__init__()` from the parent and initializes a cache.
Expand Down

0 comments on commit f77ea0a

Please sign in to comment.