Skip to content

Commit 728d4ee

Browse files
committed
Improve mypy type hints
1 parent 7e7bd87 commit 728d4ee

File tree

11 files changed

+83
-73
lines changed

11 files changed

+83
-73
lines changed

docs/Usage/Route_Operation.md

+23-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
## tag
1+
## tags
22

33
You can also specify tag for apis like this:
44

@@ -17,16 +17,17 @@ and then you will get the magic.
1717

1818
![image-20210525160744617](../assets/image-20210525160744617.png)
1919

20-
### abp_tags
20+
## abp_tags & view_tags
2121

2222
*New in v0.9.3*
2323

24-
You don't need to specify **tag** for every api.
24+
You don't need to specify **tags** for every api.
2525

26-
```python hl_lines="3"
26+
```python hl_lines="3 4"
2727
tag = Tag(name='book', description="Some Book")
2828

2929
api = APIBlueprint('/book', __name__, url_prefix='/api', abp_tags=[tag])
30+
api_view = APIView('/book', __name__, url_prefix='/api', view_tags=[tag])
3031

3132

3233
@api.post('/book')
@@ -272,6 +273,24 @@ def get_book(path: BookPath):
272273
...
273274
```
274275

276+
## abp_security & view_security
277+
278+
*New in v0.9.3*
279+
280+
You don't need to specify **security** for every api.
281+
282+
```python hl_lines="3 4"
283+
tag = Tag(name='book', description="Some Book")
284+
security = [{"jwt": []}]
285+
api = APIBlueprint('/book', __name__, abp_tags=[tag], abp_security=security)
286+
api_view = APIView('/book', __name__, abp_tags=[tag], view_security=security)
287+
288+
289+
@api.post('/book')
290+
def create_book(body: BookBody):
291+
...
292+
```
293+
275294
## servers
276295

277296
An array of Server Objects, which provide connectivity information to a target server. If the server's property is not provided, or is an empty array, the default value would be a Server Object with an url value of /.

docs/Usage/Specification.md

+13-24
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ security = [{"jwt": []}]
129129
app = OpenAPI(__name__, info=info, security_schemes=security_schemes)
130130
```
131131

132-
Second, add pass the **security** to your api, like this:
132+
Second, add pass the [**security**](./Route_Operation.md#security) to your api, like this:
133133

134134
```python hl_lines="1"
135135
@app.get('/book/<int:bid>', tags=[book_tag], security=security)
@@ -141,22 +141,6 @@ result:
141141

142142
![image-20210525165350520](../assets/image-20210525165350520.png)
143143

144-
### abp_security
145-
146-
*New in v0.9.3*
147-
148-
You don't need to specify **security** for every api.
149-
150-
```python hl_lines="3"
151-
tag = Tag(name='book', description="Some Book")
152-
security = [{"jwt": []}]
153-
api = APIBlueprint('/book', __name__, abp_tags=[tag], abp_security=security)
154-
155-
156-
@api.post('/book')
157-
def create_book(body: BookBody):
158-
...
159-
```
160144

161145
## oauth_config
162146

@@ -226,11 +210,11 @@ def endpoint():
226210
...
227211
```
228212

229-
### abp_responses
213+
## abp_responses & view_responses
230214

231215
*New in v0.9.4*
232216

233-
You can add `responses` for each API under the `api` wrapper.
217+
You can add `responses` for each API under the `api` or `api_view` wrapper.
234218

235219
```python hl_lines="10"
236220
class Unauthorized(BaseModel):
@@ -239,10 +223,15 @@ class Unauthorized(BaseModel):
239223

240224

241225
api = APIBlueprint(
242-
'/book',
226+
"/book",
243227
__name__,
244-
url_prefix='/api',
245-
abp_responses={"401": Unauthorized}
228+
url_prefix="/api",
229+
abp_responses={401: Unauthorized}
230+
)
231+
232+
api_view = APIView(
233+
"/book",
234+
view_responses={401: Unauthorized}
246235
)
247236

248237
@api.get(...)
@@ -262,15 +251,15 @@ You can also use [responses ](./Response.md#responses) and [extra_responses](./R
262251

263252
## doc_ui
264253

265-
You can pass `doc_ui=False` to disable the `OpenAPI spec` when init `OpenAPI `.
254+
You can pass `doc_ui=False` to disable the `OpenAPI spec` when init [`OpenAPI`](../Reference/OpenAPI.md).
266255

267256
```python
268257
app = OpenAPI(__name__, info=info, doc_ui=False)
269258
```
270259

271260
*New in v0.9.4*
272261

273-
You can also use `doc_ui` in endpoint or when initializing `APIBlueprint`.
262+
You can also use `doc_ui` in endpoint or when initializing [`APIBlueprint`](../Reference/APIBlueprint.md) or [`APIView`](../Reference/APIView.md).
274263

275264
```python hl_lines="4 9"
276265
api = APIBlueprint(

flask_openapi3/blueprint.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@
22
# @Author : llc
33
# @Time : 2022/4/1 16:54
44
from copy import deepcopy
5-
from typing import Optional, List, Dict, Any, Type, Callable, Tuple
5+
from typing import Optional, List, Dict, Any, Callable
66

77
from flask import Blueprint
8-
from pydantic import BaseModel
98

109
from ._http import HTTPMethod
1110
from .models import ExternalDocumentation
1211
from .models import ExtraRequestBody
1312
from .models import Server
1413
from .models import Tag
1514
from .scaffold import APIScaffold
15+
from .types import ParametersTuple
1616
from .types import ResponseDict
1717
from .utils import convert_responses_key_to_string
1818
from .utils import get_operation
@@ -119,7 +119,7 @@ def _do_decorator(
119119
openapi_extensions: Optional[Dict[str, Any]] = None,
120120
doc_ui: bool = True,
121121
method: str = HTTPMethod.GET
122-
) -> Tuple[Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel]]:
122+
) -> ParametersTuple:
123123
"""
124124
Collects OpenAPI specification information for Flask routes and view functions.
125125

flask_openapi3/models/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@
4141
from .validation_error import ValidationErrorModel
4242
from .xml import XML
4343

44-
OPENAPI3_REF_PREFIX = '#/components/schemas'
45-
OPENAPI3_REF_TEMPLATE = OPENAPI3_REF_PREFIX + '/{model}'
44+
OPENAPI3_REF_PREFIX = "#/components/schemas"
45+
OPENAPI3_REF_TEMPLATE = OPENAPI3_REF_PREFIX + "/{model}"
4646

4747

4848
class APISpec(BaseModel):

flask_openapi3/models/components.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ class Components(BaseModel):
2929
examples: Optional[Dict[str, Union[Example, Reference]]] = None
3030
requestBodies: Optional[Dict[str, Union[RequestBody, Reference]]] = None
3131
headers: Optional[Dict[str, Union[Header, Reference]]] = None
32-
securitySchemes: Optional[Dict[str, Union[SecurityScheme, Any]]] = None
32+
securitySchemes: Optional[Dict[str, Union[SecurityScheme, Dict[str, Any]]]] = None
3333
links: Optional[Dict[str, Union[Link, Reference]]] = None
3434
callbacks: Optional[Dict[str, Union[Callback, Reference]]] = None
3535
pathItems: Optional[Dict[str, Union[PathItem, Reference]]] = None

flask_openapi3/models/file.py

+2-8
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,8 @@ def __get_validators__(cls) -> Generator:
2020

2121
@classmethod
2222
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
23-
field_schema.update(
24-
format="binary",
25-
type="string"
26-
)
23+
field_schema.update(format="binary", type="string")
2724

2825
@classmethod
29-
def validate(cls, value: Any) -> '_FileStorage':
30-
if not isinstance(value, _FileStorage):
31-
raise TypeError('werkzeug.datastructures.FileStorage required')
32-
26+
def validate(cls, value: Any) -> "_FileStorage":
3327
return value

flask_openapi3/models/operation.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from .parameter import Parameter
1111
from .reference import Reference
1212
from .request_body import RequestBody
13-
from .responses import Responses
13+
from .response import Response
1414
from .security_requirement import SecurityRequirement
1515
from .server import Server
1616

@@ -25,9 +25,9 @@ class Operation(BaseModel):
2525
description: Optional[str] = None
2626
externalDocs: Optional[ExternalDocumentation] = None
2727
operationId: Optional[str] = None
28-
parameters: Optional[List[Union[Parameter, Reference]]] = None
28+
parameters: Optional[List[Parameter]] = None
2929
requestBody: Optional[Union[RequestBody, Reference]] = None
30-
responses: Optional[Responses] = None
30+
responses: Optional[Dict[str, Response]] = None
3131
callbacks: Optional[Dict[str, Callback]] = None
3232

3333
deprecated: Optional[bool] = False

flask_openapi3/openapi.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import os
66
import re
77
from copy import deepcopy
8-
from typing import Optional, List, Dict, Union, Any, Type, Callable, Tuple
8+
from typing import Optional, List, Dict, Union, Any, Type, Callable
99

1010
from flask import Flask, Blueprint, render_template_string
1111
from pydantic import BaseModel
@@ -29,6 +29,7 @@
2929
from .templates import rapidoc_html_string
3030
from .templates import redoc_html_string
3131
from .templates import swagger_html_string
32+
from .types import ParametersTuple
3233
from .types import ResponseDict
3334
from .types import SecuritySchemesDict
3435
from .utils import convert_responses_key_to_string
@@ -254,7 +255,7 @@ def api_doc(self) -> Dict:
254255

255256
# Set components
256257
self.components.schemas = self.components_schemas
257-
self.components.securitySchemes = self.security_schemes # type: ignore
258+
self.components.securitySchemes = self.security_schemes
258259
spec.components = self.components
259260

260261
# Convert spec to JSON
@@ -356,7 +357,7 @@ def _do_decorator(
356357
openapi_extensions: Optional[Dict[str, Any]] = None,
357358
doc_ui: bool = True,
358359
method: str = HTTPMethod.GET
359-
) -> Tuple[Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel]]:
360+
) -> ParametersTuple:
360361
"""
361362
Collects OpenAPI specification information for Flask routes and view functions.
362363

flask_openapi3/scaffold.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,18 @@
77
import warnings
88
from abc import ABC
99
from functools import wraps
10-
from typing import Callable, List, Optional, Dict, Type, Any, Tuple
10+
from typing import Callable, List, Optional, Dict, Any
1111

1212
from flask.scaffold import Scaffold
1313
from flask.wrappers import Response as FlaskResponse
14-
from pydantic import BaseModel
1514

1615
from ._http import HTTPMethod
1716
from .models import ExternalDocumentation
1817
from .models import ExtraRequestBody
1918
from .models import Server
2019
from .models import Tag
2120
from .request import _do_request
21+
from .types import ParametersTuple
2222
from .types import ResponseDict
2323

2424
if sys.version_info >= (3, 8):
@@ -57,7 +57,7 @@ def _do_decorator(
5757
openapi_extensions: Optional[Dict[str, Any]] = None,
5858
doc_ui: bool = True,
5959
method: str = HTTPMethod.GET
60-
) -> Tuple[Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel]]:
60+
) -> ParametersTuple:
6161
raise NotImplementedError
6262

6363
def register_api(self, api) -> None:

flask_openapi3/types.py

+11-3
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22
# @Author : llc
33
# @Time : 2023/7/9 15:25
44
from http import HTTPStatus
5-
from typing import Dict, Union, Type, Any
5+
from typing import Dict, Union, Type, Any, Tuple, Optional
66

77
from pydantic import BaseModel
88

9-
# deprecated in v3.x
10-
from .models.security import SecurityScheme
9+
from .models import SecurityScheme
1110

1211
_ResponseDictValue = Union[Type[BaseModel], Dict[Any, Any], None]
1312

@@ -16,3 +15,12 @@
1615
ResponseStrKeyDict = Dict[str, _ResponseDictValue]
1716

1817
SecuritySchemesDict = Dict[str, Union[SecurityScheme, Dict[str, Any]]]
18+
19+
ParametersTuple = Tuple[
20+
Optional[Type[BaseModel]],
21+
Optional[Type[BaseModel]],
22+
Optional[Type[BaseModel]],
23+
Optional[Type[BaseModel]],
24+
Optional[Type[BaseModel]],
25+
Optional[Type[BaseModel]]
26+
]

0 commit comments

Comments
 (0)