Skip to content

Commit 3a82dba

Browse files
author
Joel Collins
committed
Moved APISpec to a class method
1 parent ae2192a commit 3a82dba

File tree

1 file changed

+22
-47
lines changed

1 file changed

+22
-47
lines changed

src/labthings/apispec/apispec.py

Lines changed: 22 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from ..utilities import get_docstring, get_summary
66

7+
from flask.views import http_method_funcs
78
from werkzeug.routing import Rule
89
from http import HTTPStatus
910

@@ -35,50 +36,24 @@ def rule_to_apispec_path(rule: Rule, view, apispec: APISpec):
3536

3637

3738
def view_to_apispec_operations(view, apispec: APISpec):
38-
"""Generate APISpec `operations` argument from a flask View"""
39-
40-
# Build dictionary of operations (HTTP methods)
41-
ops = {}
42-
for op in ("get", "post", "put", "delete"):
43-
if hasattr(view, op):
44-
45-
ops[op] = {
46-
"description": getattr(view, "description", None)
47-
or get_docstring(view),
48-
"summary": getattr(view, "summary", None) or get_summary(view),
49-
"tags": list(view.get_tags()),
50-
}
51-
52-
# Add arguments schema
53-
if (op in (("post", "put", "delete"))) and hasattr(view, "get_args"):
54-
request_schema = convert_to_schema_or_json(view.get_args(), apispec)
55-
if request_schema:
56-
ops[op]["requestBody"] = {
57-
"content": {"application/json": {"schema": request_schema}}
58-
}
59-
60-
# Add response schema
61-
if hasattr(view, "get_responses"):
62-
ops[op]["responses"] = {}
63-
64-
for code, response in view.get_responses().items():
65-
ops[op]["responses"][code] = {
66-
"description": response.get("description")
67-
or HTTPStatus(code).phrase,
68-
"content": {
69-
# See if response description specifies a content_type
70-
# If not, assume application/json
71-
response.get("content_type", "application/json"): {
72-
"schema": convert_to_schema_or_json(
73-
response.get("schema"), apispec
74-
)
75-
}
76-
if response.get("schema")
77-
else {} # If no schema is defined, don't include one in the APISpec
78-
},
79-
}
80-
else:
81-
# If no explicit responses are known, populate with defaults
82-
ops[op]["responses"] = {200: {HTTPStatus(200).phrase}}
83-
84-
return ops
39+
specs = {}
40+
if hasattr(view, "get_apispec"):
41+
specs = view.get_apispec()
42+
43+
for method, spec in specs.items():
44+
if "responses" in spec:
45+
for response_code, response in spec["responses"].items():
46+
if "schema" in response:
47+
response["schema"] = convert_to_schema_or_json(
48+
response["schema"], apispec
49+
)
50+
51+
if "requestBody" in spec:
52+
for content_type, description in (
53+
spec["requestBody"].get("content", {}).items()
54+
):
55+
description["schema"] = convert_to_schema_or_json(
56+
description["schema"], apispec
57+
)
58+
59+
return specs

0 commit comments

Comments
 (0)