当前位置: 移动技术网 > IT编程>脚本编程>Python > Flask 系列之构建 Swagger UI 风格的 WebAPI

Flask 系列之构建 Swagger UI 风格的 WebAPI

2019年05月16日  | 移动技术网IT编程  | 我要评论

雄狮辛汉,100分seo,义乌人才网最新招聘信息

swagger ui

说明

  • 操作系统:windows 10
  • python 版本:3.7x
  • 虚拟环境管理器:virtualenv
  • 代码编辑器:vs code

实验

环境初始化

# 创建项目目录
mkdir helloworld
cd helloworld

# 创建虚拟环境
python -m virtualenv venv
# 激活虚拟环境
venv\scripts\activate

# 安装环境包
pip install flask flask-restplus

# 启动 vs code
code .

实验示例

hello world

from flask import flask
from flask_restplus import api, resource

app = flask(__name__)
api_app = api(app=app,
              version='1.0',
              title='main',
              description='main apis')
name_space = api_app.namespace(name='helloworld',
                               description='the helloworld apis endpoint.')


@name_space.route('/')
class helloworld(resource):
    def get(self):
        return {
            'status': 'you get a request.'
        }

    def post(self):
        return {
            'status': 'you post a request.'
        }


if __name__ == "__main__":
    app.run(debug=true)

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

demo

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

参数传递

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

@name_space.route('/<int:id>')
class helloworld(resource):
    @api_app.doc(responses={
        200: 'ok',
        400: 'not found',
        500: 'something is error'
    }, params={
        'id': 'the task identifier'
    })
    def get(self, id):
        return {
            'status': 'you get a request.',
            'id': id
        }

    def post(self, id):
        return {
            'status': 'you post a request.'
        }

运行结构如下图所示:

demo

实体传递

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

from flask import flask
from flask_restplus import api, resource, fields

app = flask(__name__)
api = api(app, version='1.0', title='todomvc api',
          description='a simple todomvc api',
          )

# 配置 api 空间节点
ns = api.namespace('todos', description='todo operations')

# 配置接口数据模型(此数据模型是面向对外服务的,在实际项目中应与数据库中的数据模型区分开)
todo = api.model('todo', {
    'id': fields.integer(readonly=true, description='the task unique identifier'),
    'task': fields.string(required=true, description='the task details')
})

# 定义接口实体
class tododao(object):
    def __init__(self):
        self.counter = 0
        self.todos = []

    def get(self, id):
        for todo in self.todos:
            if todo['id'] == id:
                return todo
        api.abort(404, "todo {} doesn't exist".format(id))

    def create(self, data):
        todo = data
        todo['id'] = self.counter = self.counter + 1
        self.todos.append(todo)
        return todo

    def update(self, id, data):
        todo = self.get(id)
        todo.update(data)
        return todo

    def delete(self, id):
        todo = self.get(id)
        self.todos.remove(todo)

# 创建种子数据
dao = tododao()
dao.create({'task': 'build an api'})
dao.create({'task': '?????'})
dao.create({'task': 'profit!'})

# 定义服务接口
@ns.route('/')
class todolist(resource):
    '''shows a list of all todos, and lets you post to add new tasks'''
    @ns.doc('list_todos')
    @ns.marshal_list_with(todo)
    def get(self):
        '''list all tasks'''
        return dao.todos

    @ns.doc('create_todo')
    @ns.expect(todo)
    @ns.marshal_with(todo, code=201)
    def post(self):
        '''create a new task'''
        return dao.create(api.payload), 201

# 定义服务接口
@ns.route('/<int:id>')
@ns.response(404, 'todo not found')
@ns.param('id', 'the task identifier')
class todo(resource):
    '''show a single todo item and lets you delete them'''
    @ns.doc('get_todo')
    @ns.marshal_with(todo)
    def get(self, id):
        '''fetch a given resource'''
        return dao.get(id)

    @ns.doc('delete_todo')
    @ns.response(204, 'todo deleted')
    def delete(self, id):
        '''delete a task given its identifier'''
        dao.delete(id)
        return '', 204

    @ns.expect(todo)
    @ns.marshal_with(todo)
    def put(self, id):
        '''update a task given its identifier'''
        return dao.update(id, api.payload)


if __name__ == '__main__':
    app.run(debug=true)

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

demo

总结

基于 flask 而创建 swagger ui 风格的 webapi 包有很多,如

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

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

项目参考

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网