-
-
Notifications
You must be signed in to change notification settings - Fork 146
/
loaders.py
220 lines (197 loc) · 6.27 KB
/
loaders.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# pylint: disable=too-many-arguments
import pathlib
from typing import IO, Any, Callable, Dict, Optional, Union
from urllib.parse import urljoin
import jsonschema
import requests
import yaml
from jsonschema import ValidationError
from werkzeug.test import Client
from . import spec_schemas
from .constants import USER_AGENT
from .exceptions import HTTPError
from .lazy import LazySchema
from .schemas import BaseSchema, OpenApi30, SwaggerV20
from .types import Filter, PathLike
from .utils import NOT_SET, StringDatesYAMLLoader, WSGIResponse, get_base_url
def from_path(
path: PathLike,
base_url: Optional[str] = None,
method: Optional[Filter] = None,
endpoint: Optional[Filter] = None,
tag: Optional[Filter] = None,
*,
app: Any = None,
validate_schema: bool = True,
) -> BaseSchema:
"""Load a file from OS path and parse to schema instance."""
with open(path) as fd:
return from_file(
fd,
location=pathlib.Path(path).absolute().as_uri(),
base_url=base_url,
method=method,
endpoint=endpoint,
tag=tag,
app=app,
validate_schema=validate_schema,
)
def from_uri(
uri: str,
base_url: Optional[str] = None,
method: Optional[Filter] = None,
endpoint: Optional[Filter] = None,
tag: Optional[Filter] = None,
*,
app: Any = None,
validate_schema: bool = True,
**kwargs: Any,
) -> BaseSchema:
"""Load a remote resource and parse to schema instance."""
kwargs.setdefault("headers", {}).setdefault("User-Agent", USER_AGENT)
response = requests.get(uri, **kwargs)
try:
response.raise_for_status()
except requests.HTTPError:
raise HTTPError(response=response, url=uri)
if base_url is None:
base_url = get_base_url(uri)
return from_file(
response.text,
location=uri,
base_url=base_url,
method=method,
endpoint=endpoint,
tag=tag,
app=app,
validate_schema=validate_schema,
)
def from_file(
file: Union[IO[str], str],
location: Optional[str] = None,
base_url: Optional[str] = None,
method: Optional[Filter] = None,
endpoint: Optional[Filter] = None,
tag: Optional[Filter] = None,
*,
app: Any = None,
validate_schema: bool = True,
**kwargs: Any, # needed in runner to have compatible API across all loaders
) -> BaseSchema:
"""Load a file content and parse to schema instance.
`file` could be a file descriptor, string or bytes.
"""
raw = yaml.load(file, StringDatesYAMLLoader)
return from_dict(
raw,
location=location,
base_url=base_url,
method=method,
endpoint=endpoint,
tag=tag,
app=app,
validate_schema=validate_schema,
)
def from_dict(
raw_schema: Dict[str, Any],
location: Optional[str] = None,
base_url: Optional[str] = None,
method: Optional[Filter] = None,
endpoint: Optional[Filter] = None,
tag: Optional[Filter] = None,
*,
app: Any = None,
validate_schema: bool = True,
) -> BaseSchema:
"""Get a proper abstraction for the given raw schema."""
if "swagger" in raw_schema:
_maybe_validate_schema(raw_schema, spec_schemas.SWAGGER_20, validate_schema)
return SwaggerV20(
raw_schema,
location=location,
base_url=base_url,
method=method,
endpoint=endpoint,
tag=tag,
app=app,
validate_schema=validate_schema,
)
if "openapi" in raw_schema:
_maybe_validate_schema(raw_schema, spec_schemas.OPENAPI_30, validate_schema)
return OpenApi30(
raw_schema,
location=location,
base_url=base_url,
method=method,
endpoint=endpoint,
tag=tag,
app=app,
validate_schema=validate_schema,
)
raise ValueError("Unsupported schema type")
def _maybe_validate_schema(instance: Dict[str, Any], schema: Dict[str, Any], validate_schema: bool) -> None:
if validate_schema:
try:
jsonschema.validate(instance, schema)
except TypeError as exc:
raise ValidationError("Invalid schema") from exc
def from_pytest_fixture(
fixture_name: str,
method: Optional[Filter] = NOT_SET,
endpoint: Optional[Filter] = NOT_SET,
tag: Optional[Filter] = NOT_SET,
validate_schema: bool = True,
) -> LazySchema:
"""Needed for a consistent library API."""
return LazySchema(fixture_name, method=method, endpoint=endpoint, tag=tag, validate_schema=validate_schema)
def from_wsgi(
schema_path: str,
app: Any,
base_url: Optional[str] = None,
method: Optional[Filter] = None,
endpoint: Optional[Filter] = None,
tag: Optional[Filter] = None,
validate_schema: bool = True,
**kwargs: Any,
) -> BaseSchema:
kwargs.setdefault("headers", {}).setdefault("User-Agent", USER_AGENT)
client = Client(app, WSGIResponse)
response = client.get(schema_path, **kwargs)
# Raising exception to provide unified behavior
# E.g. it will be handled in CLI - a proper error message will be shown
if 400 <= response.status_code < 600:
raise HTTPError(response=response, url=schema_path)
return from_file(
response.data,
location=schema_path,
base_url=base_url,
method=method,
endpoint=endpoint,
tag=tag,
app=app,
validate_schema=validate_schema,
)
def get_loader_for_app(app: Any) -> Callable:
if app.__class__.__module__.startswith("aiohttp."):
return from_aiohttp
return from_wsgi
def from_aiohttp(
schema_path: str,
app: Any,
base_url: Optional[str] = None,
method: Optional[Filter] = None,
endpoint: Optional[Filter] = None,
tag: Optional[Filter] = None,
*,
validate_schema: bool = True,
**kwargs: Any,
) -> BaseSchema:
from .extra._aiohttp import run_server # pylint: disable=import-outside-toplevel
port = run_server(app)
app_url = f"http://127.0.0.1:{port}/"
url = urljoin(app_url, schema_path)
if not base_url:
base_url = app_url
return from_uri(
url, base_url=base_url, method=method, endpoint=endpoint, tag=tag, validate_schema=validate_schema, **kwargs
)