| 1 |
from flask import Flask, abort |
| 2 |
from flasgger import Swagger, Schema, fields |
| 3 |
from marshmallow.validate import Length, OneOf |
| 4 |
|
| 5 |
app = Flask(__name__) |
| 6 |
Swagger(app) |
| 7 |
|
| 8 |
swag = {"swag": True, |
| 9 |
"tags": ["demo"], |
| 10 |
"responses": {200: {"description": "Success request"}, |
| 11 |
400: {"description": "Validation error"}}} |
| 12 |
|
| 13 |
|
| 14 |
class Body(Schema): |
| 15 |
color = fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"]) |
| 16 |
|
| 17 |
def swag_validation_function(self, data, main_def): |
| 18 |
self.load(data) |
| 19 |
|
| 20 |
def swag_validation_error_handler(self, err, data, main_def): |
| 21 |
""" |
| 22 |
NOTE: passing err (type of dict) to abort is supported only on flask>=1.1.0 |
| 23 |
This will trigger an error on flask<1.1.0 |
| 24 |
|
| 25 |
""" |
| 26 |
abort(400, err) |
| 27 |
|
| 28 |
|
| 29 |
class Query(Schema): |
| 30 |
color = fields.String(required=True, validate=OneOf(["white", "blue", "red"])) |
| 31 |
|
| 32 |
def swag_validation_function(self, data, main_def): |
| 33 |
self.load(data) |
| 34 |
|
| 35 |
def swag_validation_error_handler(self, err, data, main_def): |
| 36 |
abort(400, err) |
| 37 |
|
| 38 |
swag_in = "query" |
| 39 |
|
| 40 |
|
| 41 |
l |
| 42 |
@app.route("/color/<id>/<name>", methods=["POST"], **swag) |
| 43 |
def index(body: Body, query: Query, id: int, name: str): |
| 44 |
return {"body": body, "query": query, "id": id, "name": name} |
| 45 |
|
| 46 |
r |
| 47 |
@app.route("/color2/<int(signed=True):id>/<name>", methods=["POST"], **swag) |
| 48 |
def index2(body: Body, query: Query, id: int, name: str): |
| 49 |
return {"body": body, "query": query, "id": id, "name": name} |
| 50 |
|
| 51 |
from flasgger import compatible |
| 52 |
if compatible.flask_version >= compatible.v('1.1.0'): |
| 53 |
|
| 54 |
def test_swag(client, specs_data): |
| 55 |
""" |
| 56 |
This test is runs automatically in Travis CI |
| 57 |
|
| 58 |
:param client: Flask app test client |
| 59 |
:param specs_data: {'url': {swag_specs}} for every spec in app |
| 60 |
""" |
| 61 |
payload = {"color": ["white", "blue", "red"]} |
| 62 |
|
| 63 |
test_case = [ |
| 64 |
{"url": '/color/100/putin?color=white', "status_code": 200}, |
| 65 |
{"url": '/color/100/putin?color=black', "status_code": 400} |
| 66 |
] |
| 67 |
for case in test_case: |
| 68 |
response = client.post(case["url"], json=payload) |
| 69 |
assert response.status_code == case["status_code"] |
| 70 |
else: |
| 71 |
def test_swag(client, specs_data): |
| 72 |
""" |
| 73 |
This test is runs automatically in Travis CI |
| 74 |
|
| 75 |
:param client: Flask app test client |
| 76 |
:param specs_data: {'url': {swag_specs}} for every spec in app |
| 77 |
""" |
| 78 |
import logging |
| 79 |
logging.warning(f'test skipped for this flask version: {compatible.flask_version}') |
| 80 |
|
| 81 |
|
| 82 |
if __name__ == "__main__": |
| 83 |
app.run(debug=True) |