经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
Flask 系列之构建 Swagger UI 风格的 WebAPI
来源:cnblogs  作者:hippieZhou  时间:2019/5/16 9:23:30  对本文有异议

Swagger UI

说明

  • 操作系统:Windows 10
  • Python 版本:3.7x
  • 虚拟环境管理器:virtualenv
  • 代码编辑器:VS Code

实验

环境初始化

  1. # 创建项目目录
  2. mkdir helloworld
  3. cd helloworld
  4. # 创建虚拟环境
  5. python -m virtualenv venv
  6. # 激活虚拟环境
  7. venv\Scripts\activate
  8. # 安装环境包
  9. pip install flask flask-restplus
  10. # 启动 VS Code
  11. code .

实验示例

Hello World

  1. from flask import Flask
  2. from flask_restplus import Api, Resource
  3. app = Flask(__name__)
  4. api_app = Api(app=app,
  5. version='1.0',
  6. title='Main',
  7. description='Main APIs')
  8. name_space = api_app.namespace(name='helloworld',
  9. description='The helloworld APIs EndPoint.')
  10. @name_space.route('/')
  11. class HelloWorld(Resource):
  12. def get(self):
  13. return {
  14. 'status': 'you get a request.'
  15. }
  16. def post(self):
  17. return {
  18. 'status': 'you post a request.'
  19. }
  20. if __name__ == "__main__":
  21. app.run(debug=True)

程序运行效果如下图所示:

Demo

此时,我们可以通过 Swagger UI 或者 curl 来请求我们上面创建的 一个 get 和 一个 post 请求接口。

参数传递

参数传递,我们只需要将我们的接口定义添加参数配置即可,如下示例代码所示:

  1. @name_space.route('/<int:id>')
  2. class HelloWorld(Resource):
  3. @api_app.doc(responses={
  4. 200: 'ok',
  5. 400: 'not found',
  6. 500: 'something is error'
  7. }, params={
  8. 'id': 'the task identifier'
  9. })
  10. def get(self, id):
  11. return {
  12. 'status': 'you get a request.',
  13. 'id': id
  14. }
  15. def post(self, id):
  16. return {
  17. 'status': 'you post a request.'
  18. }

运行结构如下图所示:

Demo

实体传递

在上述两个示例代码中,我们知道了如何定义 WebAPI 和 参数传递,下面我们摘录一个官方首页的 Todo 示例,来完整展示如何使用:

  1. from flask import Flask
  2. from flask_restplus import Api, Resource, fields
  3. app = Flask(__name__)
  4. api = Api(app, version='1.0', title='TodoMVC API',
  5. description='A simple TodoMVC API',
  6. )
  7. # 配置 API 空间节点
  8. ns = api.namespace('todos', description='TODO operations')
  9. # 配置接口数据模型(此数据模型是面向对外服务的,在实际项目中应与数据库中的数据模型区分开)
  10. todo = api.model('Todo', {
  11. 'id': fields.Integer(readOnly=True, description='The task unique identifier'),
  12. 'task': fields.String(required=True, description='The task details')
  13. })
  14. # 定义接口实体
  15. class TodoDAO(object):
  16. def __init__(self):
  17. self.counter = 0
  18. self.todos = []
  19. def get(self, id):
  20. for todo in self.todos:
  21. if todo['id'] == id:
  22. return todo
  23. api.abort(404, "Todo {} doesn't exist".format(id))
  24. def create(self, data):
  25. todo = data
  26. todo['id'] = self.counter = self.counter + 1
  27. self.todos.append(todo)
  28. return todo
  29. def update(self, id, data):
  30. todo = self.get(id)
  31. todo.update(data)
  32. return todo
  33. def delete(self, id):
  34. todo = self.get(id)
  35. self.todos.remove(todo)
  36. # 创建种子数据
  37. DAO = TodoDAO()
  38. DAO.create({'task': 'Build an API'})
  39. DAO.create({'task': '?????'})
  40. DAO.create({'task': 'profit!'})
  41. # 定义服务接口
  42. @ns.route('/')
  43. class TodoList(Resource):
  44. '''Shows a list of all todos, and lets you POST to add new tasks'''
  45. @ns.doc('list_todos')
  46. @ns.marshal_list_with(todo)
  47. def get(self):
  48. '''List all tasks'''
  49. return DAO.todos
  50. @ns.doc('create_todo')
  51. @ns.expect(todo)
  52. @ns.marshal_with(todo, code=201)
  53. def post(self):
  54. '''Create a new task'''
  55. return DAO.create(api.payload), 201
  56. # 定义服务接口
  57. @ns.route('/<int:id>')
  58. @ns.response(404, 'Todo not found')
  59. @ns.param('id', 'The task identifier')
  60. class Todo(Resource):
  61. '''Show a single todo item and lets you delete them'''
  62. @ns.doc('get_todo')
  63. @ns.marshal_with(todo)
  64. def get(self, id):
  65. '''Fetch a given resource'''
  66. return DAO.get(id)
  67. @ns.doc('delete_todo')
  68. @ns.response(204, 'Todo deleted')
  69. def delete(self, id):
  70. '''Delete a task given its identifier'''
  71. DAO.delete(id)
  72. return '', 204
  73. @ns.expect(todo)
  74. @ns.marshal_with(todo)
  75. def put(self, id):
  76. '''Update a task given its identifier'''
  77. return DAO.update(id, api.payload)
  78. if __name__ == '__main__':
  79. app.run(debug=True)

程序运行效果如下图所示:

Demo

总结

基于 Flask 而创建 Swagger UI 风格的 WebAPI 包有很多,如

它们都各有各的优缺点,但是就我目前使用情况来说,还是 Flask-RESTPlus 的构建方式我更喜欢一些,所以我就在这里分享一下。

最后的最后,安利一下我个人站点:hippiezhou,里面的 必应壁纸 板块收录了每天的必应壁纸,希望你能喜欢。

项目参考

原文链接:http://www.cnblogs.com/hippieZhou/p/10848023.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号