Conditions | 5 |
Total Lines | 51 |
Code Lines | 38 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | """Utility functions.""" |
||
44 | def validate(spec): |
||
45 | """Decorator to validate a REST endpoint input. |
||
46 | |||
47 | Uses the schema defined in the openapi.yml file |
||
48 | to validate. |
||
49 | """ |
||
50 | |||
51 | def validate_decorator(func): |
||
52 | @functools.wraps(func) |
||
53 | def wrapper_validate(*args, **kwargs): |
||
54 | try: |
||
55 | data = request.get_json() |
||
56 | except BadRequest: |
||
57 | result = "The request body is not a well-formed JSON." |
||
58 | log.debug("create_circuit result %s %s", result, 400) |
||
59 | raise BadRequest(result) from BadRequest |
||
60 | if data is None: |
||
61 | result = "The request body mimetype is not application/json." |
||
62 | log.debug("update result %s %s", result, 415) |
||
63 | raise UnsupportedMediaType(result) |
||
64 | |||
65 | validator = RequestValidator(spec) |
||
66 | openapi_request = FlaskOpenAPIRequest(request) |
||
67 | result = validator.validate(openapi_request) |
||
68 | if result.errors: |
||
69 | errors = result.errors[0] |
||
70 | if hasattr(errors, "schema_errors"): |
||
71 | schema_errors = errors.schema_errors[0] |
||
72 | error_log = { |
||
73 | "error_message": schema_errors.message, |
||
74 | "error_validator": schema_errors.validator, |
||
75 | "error_validator_value": schema_errors.validator_value, |
||
76 | "error_path": list(schema_errors.path), |
||
77 | "error_schema": schema_errors.schema, |
||
78 | "error_schema_path": list(schema_errors.schema_path), |
||
79 | } |
||
80 | log.debug("error response: %s", error_log) |
||
81 | error_response = f"{schema_errors.message} for field" |
||
82 | error_response += ( |
||
83 | f" {'/'.join(map(str,schema_errors.path))}." |
||
84 | ) |
||
85 | else: |
||
86 | error_response = ( |
||
87 | "The request body mimetype is not application/json." |
||
88 | ) |
||
89 | raise BadRequest(error_response) from BadRequest |
||
90 | return func(*args, data=data, **kwargs) |
||
91 | |||
92 | return wrapper_validate |
||
93 | |||
94 | return validate_decorator |
||
95 |