| 1 | # Flasgger |
| 2 | ## Flask API的Easy Swagger UI |
| 3 | |
| 4 | [](https://travis-ci.com/flasgger/flasgger) |
| 5 | [](https://landscape.io/github/rochacbruno/flasgger/master) |
| 6 | [](https://coveralls.io/github/rochacbruno/flasgger?branch=master) |
| 7 | [](https://pypi.python.org/pypi/flasgger) |
| 8 | <a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=rochacbruno%40gmail%2ecom&lc=BR&item_name=Flasgger&no_note=0&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHostedGuest"><img alt='通过Paypal捐助' src='http://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif' /></a> |
| 9 | |
| 10 | |
| 11 |  |
| 12 | |
| 13 | Flasgger是一个Flask扩展,可从您的API中所有已注册的Flask视图中**提取[OpenAPI-Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operation-object)**(以下简称"spec")。 |
| 14 | |
| 15 | Flasgger还**集成 [SwaggerUI](http://swagger.io/swagger-ui/)**,因此您可以访问[http://localhost:5000/apidocs](localhost:5000/apidocs)并可视化并与您的API资源进行交互。 |
| 16 | |
| 17 | Flasgger还使用与可以验证以POST,PUT,PATCH形式接收的数据是否与**YAML**,**Python字典**,**Marshmallow Schema**所定义的spec一致。 |
| 18 | |
| 19 | Flasgger可以使用简单的函数视图或方法视图(使用docstring作为规范),或使用@swag_from装饰器从**YAML**或**dict**获取spec,还提供可以使用**SwaggerView**调用**Marshmallow Schemas**作为spec。 |
| 20 | |
| 21 | Flasgger与`Flask-RESTful`兼容,因此您可以同时使用`Resources`和`swag` spec,看看[restful示例](examples/restful.py)。 |
| 22 | |
| 23 | Flasgger还支持将`Marshmallow APISpec`作为规范的spec模板,如果您使用的是Marshmallow的APISPec,请查看[apispec示例](examples/apispec_example.py)。 |
| 24 | |
| 25 | # 高度参与的贡献者 |
| 26 | |
| 27 | [](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/0)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/1)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/2)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/3)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/4)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/5)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/6)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/7) |
| 28 | |
| 29 | # 示例和演示应用 |
| 30 | |
| 31 | 有一些[示例应用程序](examples/) ,您也可以在[Flasgger演示应用程序](http://flasgger.pythonanywhere.com/)中使用示例。 |
| 32 | |
| 33 | > 注意:所有示例应用程序也是测试用例,并在Travis CI中自动运行以确保质量和测试覆盖范围。 |
| 34 | |
| 35 | ## Docker |
| 36 | |
| 37 | 示例和演示应用程序也可以作为Docker映像/容器构建和运行: |
| 38 | |
| 39 | ``` |
| 40 | docker build -t flasgger . |
| 41 | docker run -it --rm -p 5000:5000 --name flasgger flasgger |
| 42 | ``` |
| 43 | 然后访问位于 http://localhost:5000 的Flasgger演示应用程序。 |
| 44 | |
| 45 | # 安装 |
| 46 | |
| 47 | > 在您的virtualenv下执行以下操作: |
| 48 | |
| 49 | 确保您拥有最新的setuptools |
| 50 | ``` |
| 51 | pip install -U setuptools |
| 52 | ``` |
| 53 | |
| 54 | 然后 |
| 55 | |
| 56 | ``` |
| 57 | pip install flasgger |
| 58 | ``` |
| 59 | |
| 60 | 或(开发版本) |
| 61 | |
| 62 | ``` |
| 63 | pip install https://github.com/flasgger/flasgger/tarball/master |
| 64 | ``` |
| 65 | |
| 66 | > 注意:如果要使用**Marshmallow Schemas**,则还需要运行`pip install marshmallow apispec`。 |
| 67 | |
| 68 | # 入门 |
| 69 | |
| 70 | ## 使用文档字符串作为spec |
| 71 | |
| 72 | |
| 73 | 创建一个名为`colors.py`的文件 |
| 74 | |
| 75 | ```python |
| 76 | from flask import Flask, jsonify |
| 77 | from flasgger import Swagger |
| 78 | |
| 79 | app = Flask(__name__) |
| 80 | swagger = Swagger(app) |
| 81 | |
| 82 | @app.route('/colors/<palette>/') |
| 83 | def colors(palette): |
| 84 | """示例端点按调色板返回颜色列表 |
| 85 | 这是使用文档字符串作为spec。 |
| 86 | --- |
| 87 | parameters: |
| 88 | - name: palette |
| 89 | in: path |
| 90 | type: string |
| 91 | enum: ['all', 'rgb', 'cmyk'] |
| 92 | required: true |
| 93 | default: all |
| 94 | definitions: |
| 95 | Palette: |
| 96 | type: object |
| 97 | properties: |
| 98 | palette_name: |
| 99 | type: array |
| 100 | items: |
| 101 | $ref: '#/definitions/Color' |
| 102 | Color: |
| 103 | type: string |
| 104 | responses: |
| 105 | 200: |
| 106 | description: 颜色列表(可被调色板过滤) |
| 107 | schema: |
| 108 | $ref: '#/definitions/Palette' |
| 109 | examples: |
| 110 | rgb: ['red', 'green', 'blue'] |
| 111 | """ |
| 112 | all_colors = { |
| 113 | 'cmyk': ['cyan', 'magenta', 'yellow', 'black'], |
| 114 | 'rgb': ['red', 'green', 'blue'] |
| 115 | } |
| 116 | if palette == 'all': |
| 117 | result = all_colors |
| 118 | else: |
| 119 | result = {palette: all_colors.get(palette)} |
| 120 | |
| 121 | return jsonify(result) |
| 122 | |
| 123 | app.run(debug=True) |
| 124 | ``` |
| 125 | |
| 126 | 现在运行: |
| 127 | |
| 128 | ``` |
| 129 | python colors.py |
| 130 | ``` |
| 131 | |
| 132 | 并转到:[http://localhost:5000/apidocs/](http://localhost:5000/apidocs/) |
| 133 | |
| 134 | 您应该得到: |
| 135 | |
| 136 |  |
| 137 | |
| 138 | ## 使用外部YAML文件 |
| 139 | |
| 140 | 保存一个新文件`colors.yml` |
| 141 | |
| 142 | ```yaml |
| 143 | 示例端点按调色板返回颜色列表 |
| 144 | 在此示例中,规范取自外部YAML文件 |
| 145 | --- |
| 146 | parameters: |
| 147 | - name: palette |
| 148 | in: path |
| 149 | type: string |
| 150 | enum: ['all', 'rgb', 'cmyk'] |
| 151 | required: true |
| 152 | default: all |
| 153 | definitions: |
| 154 | Palette: |
| 155 | type: object |
| 156 | properties: |
| 157 | palette_name: |
| 158 | type: array |
| 159 | items: |
| 160 | $ref: '#/definitions/Color' |
| 161 | Color: |
| 162 | type: string |
| 163 | responses: |
| 164 | 200: |
| 165 | description: 颜色列表(可被调色板过滤) |
| 166 | schema: |
| 167 | $ref: '#/definitions/Palette' |
| 168 | examples: |
| 169 | rgb: ['red', 'green', 'blue'] |
| 170 | ``` |
| 171 | |
| 172 | |
| 173 | 让我们使用相同的示例,仅更改视图功能。 |
| 174 | |
| 175 | ```python |
| 176 | from flasgger import swag_from |
| 177 | |
| 178 | @app.route('/colors/<palette>/') |
| 179 | @swag_from('colors.yml') |
| 180 | def colors(palette): |
| 181 | ... |
| 182 | ``` |
| 183 | |
| 184 | 如果您不想使用装饰器,则可以使用docstring`file:`快捷方式。 |
| 185 | |
| 186 | ```python |
| 187 | @app.route('/colors/<palette>/') |
| 188 | def colors(palette): |
| 189 | """ |
| 190 | file: colors.yml |
| 191 | """ |
| 192 | ... |
| 193 | ``` |
| 194 | |
| 195 | |
| 196 | ## 使用字典作为raw spec |
| 197 | |
| 198 | 创建一个Python字典为: |
| 199 | |
| 200 | ```python |
| 201 | specs_dict = { |
| 202 | "parameters": [ |
| 203 | { |
| 204 | "name": "palette", |
| 205 | "in": "path", |
| 206 | "type": "string", |
| 207 | "enum": [ |
| 208 | "all", |
| 209 | "rgb", |
| 210 | "cmyk" |
| 211 | ], |
| 212 | "required": "true", |
| 213 | "default": "all" |
| 214 | } |
| 215 | ], |
| 216 | "definitions": { |
| 217 | "Palette": { |
| 218 | "type": "object", |
| 219 | "properties": { |
| 220 | "palette_name": { |
| 221 | "type": "array", |
| 222 | "items": { |
| 223 | "$ref": "#/definitions/Color" |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | }, |
| 228 | "Color": { |
| 229 | "type": "string" |
| 230 | } |
| 231 | }, |
| 232 | "responses": { |
| 233 | "200": { |
| 234 | "description": "颜色列表(可被调色板过滤)", |
| 235 | "schema": { |
| 236 | "$ref": "#/definitions/Palette" |
| 237 | }, |
| 238 | "examples": { |
| 239 | "rgb": [ |
| 240 | "red", |
| 241 | "green", |
| 242 | "blue" |
| 243 | ] |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | ``` |
| 249 | |
| 250 | 现在为同一个函数使用dict替代YAML文件。 |
| 251 | |
| 252 | ```python |
| 253 | @app.route('/colors/<palette>/') |
| 254 | @swag_from(specs_dict) |
| 255 | def colors(palette): |
| 256 | """Example endpoint returning a list of colors by palette |
| 257 | In this example the specification is taken from specs_dict |
| 258 | """ |
| 259 | ... |
| 260 | ``` |
| 261 | |
| 262 | ## 使用 Marshmallow Schemas |
| 263 | |
| 264 | > 首先: `pip install marshmallow apispec` |
| 265 | |
| 266 | ```python |
| 267 | from flask import Flask, jsonify |
| 268 | from flasgger import Swagger, SwaggerView, Schema, fields |
| 269 | |
| 270 | |
| 271 | class Color(Schema): |
| 272 | name = fields.Str() |
| 273 | |
| 274 | class Palette(Schema): |
| 275 | pallete_name = fields.Str() |
| 276 | colors = fields.Nested(Color, many=True) |
| 277 | |
| 278 | class PaletteView(SwaggerView): |
| 279 | parameters = [ |
| 280 | { |
| 281 | "name": "palette", |
| 282 | "in": "path", |
| 283 | "type": "string", |
| 284 | "enum": ["all", "rgb", "cmyk"], |
| 285 | "required": True, |
| 286 | "default": "all" |
| 287 | } |
| 288 | ] |
| 289 | responses = { |
| 290 | 200: { |
| 291 | "description": "颜色列表(可被调色板过滤)", |
| 292 | "schema": Palette |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | def get(self, palette): |
| 297 | """ |
| 298 | Colors API using schema |
| 299 | This example is using marshmallow schemas |
| 300 | """ |
| 301 | all_colors = { |
| 302 | 'cmyk': ['cyan', 'magenta', 'yellow', 'black'], |
| 303 | 'rgb': ['red', 'green', 'blue'] |
| 304 | } |
| 305 | if palette == 'all': |
| 306 | result = all_colors |
| 307 | else: |
| 308 | result = {palette: all_colors.get(palette)} |
| 309 | return jsonify(result) |
| 310 | |
| 311 | app = Flask(__name__) |
| 312 | swagger = Swagger(app) |
| 313 | |
| 314 | app.add_url_rule( |
| 315 | '/colors/<palette>', |
| 316 | view_func=PaletteView.as_view('colors'), |
| 317 | methods=['GET'] |
| 318 | ) |
| 319 | |
| 320 | app.run(debug=True) |
| 321 | |
| 322 | ``` |
| 323 | |
| 324 | > 注意:请查看`examples/validation.py`,以获得更完整的示例。 |
| 325 | |
| 326 | |
| 327 | > 注意:在路径规则(path rule)中捕获参数时,请始终使用显式类型,不可以:``/api/<username>`` 可以:``/api/<string:username>`` |
| 328 | |
| 329 | |
| 330 | ## 使用 **Flask RESTful** 资源 (Resources) |
| 331 | |
| 332 | Flasgger与Flask-RESTful兼容,您只需要安装`pip install flask-restful`,然后: |
| 333 | |
| 334 | ```python |
| 335 | |
| 336 | from flask import Flask |
| 337 | from flasgger import Swagger |
| 338 | from flask_restful import Api, Resource |
| 339 | |
| 340 | app = Flask(__name__) |
| 341 | api = Api(app) |
| 342 | swagger = Swagger(app) |
| 343 | |
| 344 | class Username(Resource): |
| 345 | def get(self, username): |
| 346 | """ |
| 347 | 本示例使用FlaskRESTful资源 |
| 348 | 它也适用于swag_from,schema和spec_dict |
| 349 | --- |
| 350 | parameters: |
| 351 | - in: path |
| 352 | name: username |
| 353 | type: string |
| 354 | required: true |
| 355 | responses: |
| 356 | 200: |
| 357 | description: 单个用户项 |
| 358 | schema: |
| 359 | id: User |
| 360 | properties: |
| 361 | username: |
| 362 | type: string |
| 363 | description: 用户名 |
| 364 | default: 匿名用户 |
| 365 | """ |
| 366 | return {'username': username}, 200 |
| 367 | |
| 368 | |
| 369 | api.add_resource(Username, '/username/<username>') |
| 370 | |
| 371 | app.run(debug=True) |
| 372 | |
| 373 | ``` |
| 374 | |
| 375 | ## 自动解析外部YAML文档和 `MethodView`s |
| 376 | |
| 377 | 可以将Flasgger配置为自动解析外部YAML API文档。在您的 `app.config['SWAGGER']`中设置[Set a `doc_dir`](https://github.com/rochacbruno/flasgger/blob/aaef05c17cc559d01b7436211093463642eb6ae2/examples/parsed_view_func.py#L16),然后Swagger将加载API文档通过在doc_dir中查找由端点名称和函数名称存储的YAML文件。例如,`'doc_dir': './examples/docs/'`和文件`./examples/docs/items/get.yml`将为`ItemsView`方法`get`提供Swagger文档。 |
| 378 | |
| 379 | 另外,当如上使用**Flask RESTful**时,通过在构造`Swagger`时传递`parse=True`,Flasgger将使用`flask_restful.reqparse.RequestParser`,找到所有`MethodView`s,然后将解析和验证的数据存储在flask.request.parsed_data中。 |
| 380 | |
| 381 | ## 为单个函数处理多个http方法和路由 |
| 382 | |
| 383 | 您可以按端点或函数分隔spec |
| 384 | |
| 385 | ```python |
| 386 | from flasgger.utils import swag_from |
| 387 | |
| 388 | @app.route('/api/<string:username>', endpoint='with_user_name', methods=['PUT', 'GET']) |
| 389 | @app.route('/api/', endpoint='without_user_name') |
| 390 | @swag_from('path/to/external_file.yml', endpoint='with_user_name') |
| 391 | @swag_from('path/to/external_file_no_user_get.yml', endpoint='without_user_name', methods=['GET']) |
| 392 | @swag_from('path/to/external_file_no_user_put.yml', endpoint='without_user_name', methods=['PUT']) |
| 393 | def fromfile_decorated(username=None): |
| 394 | if not username: |
| 395 | return "No user!" |
| 396 | return jsonify({'username': username}) |
| 397 | ``` |
| 398 | |
| 399 | 同样,可以通过多次注册url_rule实现在同一个`MethodView`或`SwaggerView`中使用多个函数。`examples/example_app` |
| 400 | |
| 401 | |
| 402 | # 使用相同的数据来验证API POST主体(body)。 |
| 403 | |
| 404 | 将`swag_from`的`_validation_`参数设置为`True`会自动验证传入的数据: |
| 405 | |
| 406 | ```python |
| 407 | from flasgger import swag_from |
| 408 | |
| 409 | @swag_from('defs.yml', validation=True) |
| 410 | def post(): |
| 411 | # 如果未通过验证,则返回状态为400的ValidationError响应并还返回验证消息。 |
| 412 | ``` |
| 413 | |
| 414 | 也可以使用`swagger.validate`注释: |
| 415 | |
| 416 | ```python |
| 417 | from flasgger import Swagger |
| 418 | |
| 419 | swagger = Swagger(app) |
| 420 | |
| 421 | @swagger.validate('UserSchema') |
| 422 | def post(): |
| 423 | ''' |
| 424 | file: defs.yml |
| 425 | ''' |
| 426 | # 如果未通过验证,则返回状态为400的ValidationError响应并还返回验证消息。 |
| 427 | ``` |
| 428 | |
| 429 | Yet you can call `validate` manually: |
| 430 | |
| 431 | ```python |
| 432 | from flasgger import swag_from, validate |
| 433 | |
| 434 | @swag_from('defs.yml') |
| 435 | def post(): |
| 436 | validate(request.json, 'UserSchema', 'defs.yml') |
| 437 | # 如果未通过验证,则返回状态为400的ValidationError响应并还返回验证消息。 |
| 438 | ``` |
| 439 | |
| 440 | 也可以在`SwaggerView`中定义`validation=True`并使用 |
| 441 | `specs_dict`用于验证。 |
| 442 | |
| 443 | 请查看`examples/validation.py`了解更多信息。 |
| 444 | |
| 445 | 所有验证选项均可在 http://json-schema.org/latest/json-schema-validation.html 找到 |
| 446 | |
| 447 | ### 自定义验证 |
| 448 | |
| 449 | 默认情况下,Flasgger将使用[python-jsonschema](https://python-jsonschema.readthedocs.io/en/latest/) |
| 450 | 执行验证。 |
| 451 | |
| 452 | 只要满足要求,就支持自定义验证功能: |
| 453 | - 仅接受两个位置参数: |
| 454 | - 首先要验证的数据;和 |
| 455 | - 作为第二个参数验证的schema |
| 456 | - 验证失败时引发任何形式的异常。 |
| 457 | |
| 458 | 任何返回值都将被丢弃。 |
| 459 | |
| 460 | |
| 461 | 向Swagger实例提供函数将使其成为默认值: |
| 462 | |
| 463 | ```python |
| 464 | from flasgger import Swagger |
| 465 | |
| 466 | swagger = Swagger(app, validation_function=my_validation_function) |
| 467 | ``` |
| 468 | |
| 469 | 提供函数作为`swag_from`或`swagger.validate`的参数 |
| 470 | 批注或直接添加到`validate`函数将强制使用它 |
| 471 | 而不是Swagger的默认验证功能: |
| 472 | ```python |
| 473 | from flasgger import swag_from |
| 474 | |
| 475 | @swag_from('spec.yml', validation=True, validation_function=my_function) |
| 476 | ... |
| 477 | ``` |
| 478 | |
| 479 | ```python |
| 480 | from flasgger import Swagger |
| 481 | |
| 482 | swagger = Swagger(app) |
| 483 | |
| 484 | @swagger.validate('Pet', validation_function=my_function) |
| 485 | ... |
| 486 | ``` |
| 487 | |
| 488 | ```python |
| 489 | from flasgger import validate |
| 490 | |
| 491 | ... |
| 492 | |
| 493 | validate( |
| 494 | request.json, 'Pet', 'defs.yml', validation_function=my_function) |
| 495 | ``` |
| 496 | |
| 497 | ### 验证错误处理 |
| 498 | |
| 499 | 默认情况下,Flasgger处理验证错误的方式是中止请求(abort)并返回 |
| 500 | 带有错误消息的400 BAD REQUEST响应。 |
| 501 | |
| 502 | 可以提供自定义验证错误处理函数(custom validation error handling function) |
| 503 | 只要符合要求,就会取代默认行为: |
| 504 | - 接受三个且仅三个位置参数: |
| 505 | - 抛出的error |
| 506 | - 造成验证失败的数据;和 |
| 507 | - 用于验证的schema |
| 508 | |
| 509 | |
| 510 | 向Swagger实例提供函数将使其成为默认值: |
| 511 | |
| 512 | ```python |
| 513 | from flasgger import Swagger |
| 514 | |
| 515 | swagger = Swagger(app, validation_error_handler=my_handler) |
| 516 | ``` |
| 517 | 提供这个函数作为`swag_from`或`swagger.validate`批注的参数 |
| 518 | 或直接添加到`validate`函数都将强制使用它 |
| 519 | 而不是Swagger的默认验证功能: |
| 520 | ```python |
| 521 | from flasgger import swag_from |
| 522 | |
| 523 | @swag_from( |
| 524 | 'spec.yml', validation=True, validation_error_handler=my_handler) |
| 525 | ... |
| 526 | ``` |
| 527 | |
| 528 | ```python |
| 529 | from flasgger import Swagger |
| 530 | |
| 531 | swagger = Swagger(app) |
| 532 | |
| 533 | @swagger.validate('Pet', validation_error_handler=my_handler) |
| 534 | ... |
| 535 | ``` |
| 536 | |
| 537 | ```python |
| 538 | from flasgger import validate |
| 539 | |
| 540 | ... |
| 541 | |
| 542 | validate( |
| 543 | request.json, 'Pet', 'defs.yml', |
| 544 | validation_error_handler=my_handler) |
| 545 | ``` |
| 546 | |
| 547 | 使用自定义验证错误处理函数的应用示例: |
| 548 | 见 [example validation_error_handler.py](examples/validation_error_handler.py) |
| 549 | |
| 550 | # 获取已定义的schema作为python词 |
| 551 | |
| 552 | 您可能希望不复制spec而将在Swagger spec中定义schemas用作字典。 |
| 553 | 为此,您可以使用`get_schema` |
| 554 | 函数: |
| 555 | |
| 556 | ```python |
| 557 | from flask import Flask, jsonify |
| 558 | from flasgger import Swagger, swag_from |
| 559 | |
| 560 | app = Flask(__name__) |
| 561 | swagger = Swagger(app) |
| 562 | |
| 563 | @swagger.validate('Product') |
| 564 | def post(): |
| 565 | """ |
| 566 | post endpoint |
| 567 | --- |
| 568 | tags: |
| 569 | - products |
| 570 | parameters: |
| 571 | - name: body |
| 572 | in: body |
| 573 | required: true |
| 574 | schema: |
| 575 | id: Product |
| 576 | required: |
| 577 | - name |
| 578 | properties: |
| 579 | name: |
| 580 | type: string |
| 581 | description: The product's name. |
| 582 | default: "Guarana" |
| 583 | responses: |
| 584 | 200: |
| 585 | description: The product inserted in the database |
| 586 | schema: |
| 587 | $ref: '#/definitions/Product' |
| 588 | """ |
| 589 | rv = db.insert(request.json) |
| 590 | return jsonify(rv) |
| 591 | |
| 592 | ... |
| 593 | |
| 594 | product_schema = swagger.get_schema('product') |
| 595 | ``` |
| 596 | |
| 597 | 此方法返回包含Flasgger schema id的字典, |
| 598 | 所有定义的参数和所需参数的列表。 |
| 599 | |
| 600 | # HTML清理器(HTML sanitizer) |
| 601 | |
| 602 | 默认情况下,Flasgger将尝试清理YAML定义中的内容 |
| 603 | 用```<br>```替换每个`\n`,但是您可以更改此行为 |
| 604 | 设置另一种清理器。 |
| 605 | |
| 606 | ```python |
| 607 | from flasgger import Swagger, NO_SANITIZER |
| 608 | |
| 609 | app =Flask() |
| 610 | swagger = Swagger(app, sanitizer=NO_SANITIZER) |
| 611 | ``` |
| 612 | |
| 613 | 您可以自行编写清理器 |
| 614 | |
| 615 | ```python |
| 616 | swagger = Swagger(app, sanitizer=lambda text: do_anything_with(text)) |
| 617 | ``` |
| 618 | |
| 619 | 如果您希望能够渲染您的specs description中的Markdown,还可以使用Markdown解析器**MK_SANITIZER** |
| 620 | |
| 621 | |
| 622 | # Swagger UI和模板 |
| 623 | |
| 624 | 您可以在应用程序中重写(override) `templates/flasgger/index.html`, |
| 625 | 重写后的模板将为SwaggerUI的`index.html`。使用`flasgger/ui2/templates/index.html` |
| 626 | 作为您自定义`index.html`文件的基础。 |
| 627 | |
| 628 | Flasgger支持Swagger UI版本2和3。版本3仍处于试验阶段,但是您 |
| 629 | 可以尝试设置`app.config['SWAGGER']['uiversion']`. |
| 630 | |
| 631 | ```python |
| 632 | app = Flask(__name__) |
| 633 | app.config['SWAGGER'] = { |
| 634 | 'title': 'My API', |
| 635 | 'uiversion': 3 |
| 636 | } |
| 637 | swagger = Swagger(app) |
| 638 | |
| 639 | ``` |
| 640 | |
| 641 | # OpenAPI 3.0支持 |
| 642 | |
| 643 | 对OpenAPI 3.0的实验性支持应该在使用SwaggerUI 3时起作用。要使用OpenAPI 3.0,请将`app.config['SWAGGER']['openapi']` 设置为当前SwaggerUI 3支持的版本,例如`'3.0.2'`。 |
| 644 | |
| 645 | 有关使用`callbacks`和`requestBody`的示例,请参见[callbacks example](examples/callbacks.py)。 |
| 646 | |
| 647 | ## 从外部加载Swagger UI和jQuery JS/CSS |
| 648 | |
| 649 | 从Flasgger 0.9.2开始,您可以指定外部URL位置,以为Flasgger默认模板中加载的Swagger和jQuery库加载JavaScript和CSS。如果省略以下配置属性,则Flasgger将提供它所包含的静态版本-这些版本可能比当前的Swagger UI v2或v3版本要旧。 |
| 650 | |
| 651 | 以下示例从unpkg.com加载Swagger UI和jQuery版本: |
| 652 | |
| 653 | ``` |
| 654 | swagger_config = Swagger.DEFAULT_CONFIG |
| 655 | swagger_config['swagger_ui_bundle_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js' |
| 656 | swagger_config['swagger_ui_standalone_preset_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js' |
| 657 | swagger_config['jquery_js'] = '//unpkg.com/[email protected]/dist/jquery.min.js' |
| 658 | swagger_config['swagger_ui_css'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui.css' |
| 659 | Swagger(app, config=swagger_config) |
| 660 | ``` |
| 661 | |
| 662 | # Initializing Flasgger with default data. |
| 663 | |
| 664 | 您可以使用默认数据来启动Swagger spec或提供模板: |
| 665 | |
| 666 | ```python |
| 667 | template = { |
| 668 | "swagger": "2.0", |
| 669 | "info": { |
| 670 | "title": "My API", |
| 671 | "description": "API for my data", |
| 672 | "contact": { |
| 673 | "responsibleOrganization": "ME", |
| 674 | "responsibleDeveloper": "Me", |
| 675 | "email": "[email protected]", |
| 676 | "url": "www.me.com", |
| 677 | }, |
| 678 | "termsOfService": "http://me.com/terms", |
| 679 | "version": "0.0.1" |
| 680 | }, |
| 681 | "host": "mysite.com", # overrides localhost:500 |
| 682 | "basePath": "/api", # base bash for blueprint registration |
| 683 | "schemes": [ |
| 684 | "http", |
| 685 | "https" |
| 686 | ], |
| 687 | "operationId": "getmyData" |
| 688 | } |
| 689 | |
| 690 | swagger = Swagger(app, template=template) |
| 691 | |
| 692 | ``` |
| 693 | |
| 694 | And then the template is the default data unless some view changes it. You |
| 695 | can also provide all your specs as template and have no views. Or views in |
| 696 | external APP. |
| 697 | |
| 698 | 然后,除非某些视图更改了模板,否则模板是默认数据。您 |
| 699 | 也可以提供所有spec作为模板,而无需包括视图。或 |
| 700 | 外部APP中的视图。 |
| 701 | |
| 702 | ## #在运行时获取默认数据 |
| 703 | |
| 704 | 有时您需要在运行时获取一些数据,具体取决于动态值,例如:要检查`request.is_secure`以确定`schemes`是否为`https`,您可以使用`LazyString`做到这一点。 |
| 705 | |
| 706 | ```py |
| 707 | from flask import Flask |
| 708 | from flasgger import, Swagger, LazyString, LazyJSONEncoder |
| 709 | |
| 710 | app = Flask(__init__) |
| 711 | |
| 712 | # 设置自定义编码器(如果需要自定义,则继承它) |
| 713 | app.json_encoder = LazyJSONEncoder |
| 714 | |
| 715 | |
| 716 | template = dict( |
| 717 | info={ |
| 718 | 'title': LazyString(lambda: 'Lazy Title'), |
| 719 | 'version': LazyString(lambda: '99.9.9'), |
| 720 | 'description': LazyString(lambda: 'Hello Lazy World'), |
| 721 | 'termsOfService': LazyString(lambda: '/there_is_no_tos') |
| 722 | }, |
| 723 | host=LazyString(lambda: request.host), |
| 724 | schemes=[LazyString(lambda: 'https' if request.is_secure else 'http')], |
| 725 | foo=LazyString(lambda: "Bar") |
| 726 | ) |
| 727 | Swagger(app, template=template) |
| 728 | |
| 729 | ``` |
| 730 | |
| 731 | The `LazyString` values will be evaluated only when `jsonify` encodes the value at runtime, so you have access to Flask `request, session, g, etc..` and also may want to access a database. |
| 732 | 仅当`jsonify`在运行时对该值进行编码时,才会评估`LazyString`的值,因此您可以访问Flask的`request,session,g 等`,或者是访问数据库。 |
| 733 | |
| 734 | ## 经过反向代理 |
| 735 | |
| 736 | 有时,您是在反向代理(例如NGINX)后面提供庞大的文档。当遵循[Flask指南](http://flask.pocoo.org/snippets/35/)时, |
| 737 | Swagger的文档将正确加载,但是“尝试一下”按钮指向错误的位置。可以使用以下代码解决此问题: |
| 738 | |
| 739 | ```python |
| 740 | from flask import Flask, request |
| 741 | from flasgger import Swagger, LazyString, LazyJSONEncoder |
| 742 | |
| 743 | app = Flask(__name__) |
| 744 | app.json_encoder = LazyJSONEncoder |
| 745 | |
| 746 | template = dict(swaggerUiPrefix=LazyString(lambda : request.environ.get('HTTP_X_SCRIPT_NAME', ''))) |
| 747 | swagger = Swagger(app, template=template) |
| 748 | |
| 749 | ``` |
| 750 | |
| 751 | # 自定义默认配置 |
| 752 | |
| 753 | 可以向Flasgger提供自定义配置,例如不同的spec route或禁用Swagger UI: |
| 754 | |
| 755 | ```python |
| 756 | swagger_config = { |
| 757 | "headers": [ |
| 758 | ], |
| 759 | "specs": [ |
| 760 | { |
| 761 | "endpoint": 'apispec_1', |
| 762 | "route": '/apispec_1.json', |
| 763 | "rule_filter": lambda rule: True, # all in |
| 764 | "model_filter": lambda tag: True, # all in |
| 765 | } |
| 766 | ], |
| 767 | "static_url_path": "/flasgger_static", |
| 768 | # "static_folder": "static", # must be set by user |
| 769 | "swagger_ui": True, |
| 770 | "specs_route": "/apidocs/" |
| 771 | } |
| 772 | |
| 773 | swagger = Swagger(app, config=swagger_config) |
| 774 | |
| 775 | ``` |
| 776 | |
| 777 | ## 提取定义 |
| 778 | |
| 779 | 当在spec中找到`id`时,可以提取定义,例如: |
| 780 | |
| 781 | ```python |
| 782 | from flask import Flask, jsonify |
| 783 | from flasgger import Swagger |
| 784 | |
| 785 | app = Flask(__name__) |
| 786 | swagger = Swagger(app) |
| 787 | |
| 788 | @app.route('/colors/<palette>/') |
| 789 | def colors(palette): |
| 790 | """Example endpoint returning a list of colors by palette |
| 791 | --- |
| 792 | parameters: |
| 793 | - name: palette |
| 794 | in: path |
| 795 | type: string |
| 796 | enum: ['all', 'rgb', 'cmyk'] |
| 797 | required: true |
| 798 | default: all |
| 799 | responses: |
| 800 | 200: |
| 801 | description: 颜色列表(可被调色板过滤) |
| 802 | schema: |
| 803 | id: Palette |
| 804 | type: object |
| 805 | properties: |
| 806 | palette_name: |
| 807 | type: array |
| 808 | items: |
| 809 | schema: |
| 810 | id: Color |
| 811 | type: string |
| 812 | examples: |
| 813 | rgb: ['red', 'green', 'blue'] |
| 814 | """ |
| 815 | all_colors = { |
| 816 | 'cmyk': ['cyan', 'magenta', 'yellow', 'black'], |
| 817 | 'rgb': ['red', 'green', 'blue'] |
| 818 | } |
| 819 | if palette == 'all': |
| 820 | result = all_colors |
| 821 | else: |
| 822 | result = {palette: all_colors.get(palette)} |
| 823 | |
| 824 | return jsonify(result) |
| 825 | |
| 826 | app.run(debug=True) |
| 827 | ``` |
| 828 | |
| 829 | 在此示例中,您不必传递`definitions`,而是需要将`id`添加到您的schema。 |
| 830 | |
| 831 | ## Python2兼容性 |
| 832 | |
| 833 | |
| 834 | 版本`0.9.5.*`将是最后一个支持Python2的版本。 |
| 835 | 请在这里讨论[#399](https://github.com/flasgger/flasgger/issues/399)。 |
| 836 |