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
|
# Flask
This section describes integration with the [Flask](https://flask.palletsprojects.com) web framework.
## View decorator
Flask can be integrated using a [view decorator](https://flask.palletsprojects.com/en/latest/patterns/viewdecorators/) to apply OpenAPI validation to your application's specific views.
Use `FlaskOpenAPIViewDecorator` with the OpenAPI object to create the decorator.
``` python hl_lines="1 3 6"
from openapi_core.contrib.flask.decorators import FlaskOpenAPIViewDecorator
openapi_validated = FlaskOpenAPIViewDecorator(openapi)
@app.route('/home')
@openapi_validated
def home():
return "Welcome home"
```
You can skip the response validation process by setting `response_cls` to `None`.
``` python hl_lines="5"
from openapi_core.contrib.flask.decorators import FlaskOpenAPIViewDecorator
openapi_validated = FlaskOpenAPIViewDecorator(
openapi,
response_cls=None,
)
```
If you want to decorate a class-based view, you can use the `decorators` attribute:
``` python hl_lines="2"
class MyView(View):
decorators = [openapi_validated]
def dispatch_request(self):
return "Welcome home"
app.add_url_rule('/home', view_func=MyView.as_view('home'))
```
## View
As an alternative to the decorator-based integration, Flask method-based views can be integrated by inheriting from the `FlaskOpenAPIView` class.
``` python hl_lines="1 3 8"
from openapi_core.contrib.flask.views import FlaskOpenAPIView
class MyView(FlaskOpenAPIView):
def get(self):
return "Welcome home"
app.add_url_rule(
'/home',
view_func=MyView.as_view('home', spec),
)
```
Additional customization parameters can be passed to the view.
``` python hl_lines="10"
from openapi_core.contrib.flask.views import FlaskOpenAPIView
class MyView(FlaskOpenAPIView):
def get(self):
return "Welcome home"
app.add_url_rule(
'/home',
view_func=MyView.as_view(
'home', spec,
extra_format_validators=extra_format_validators,
),
)
```
## Request parameters
In Flask, all unmarshalled request data are provided as the Flask request object's `openapi.parameters` attribute.
``` python hl_lines="6 7"
from flask.globals import request
@app.route('/browse/<id>/')
@openapi
def browse(id):
browse_id = request.openapi.parameters.path['id']
page = request.openapi.parameters.query.get('page', 1)
return f"Browse {browse_id}, page {page}"
```
## Low level
You can use `FlaskOpenAPIRequest` as a Flask request factory:
```python
from openapi_core.contrib.flask import FlaskOpenAPIRequest
openapi_request = FlaskOpenAPIRequest(flask_request)
result = openapi.unmarshal_request(openapi_request)
```
For the response factory, see the [Werkzeug](werkzeug.md) integration.
|