iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Flask 系列之 构建 Swagger
  • 559
分享到

Flask 系列之 构建 Swagger

系列之FlaskSwagger 2023-01-31 00:01:33 559人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

说明 操作系统:windows 10 python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验 环境初始化 # 创建项目目录 mkdir helloworld cd helloworld

Swagger UI

说明

实验

环境初始化

# 创建项目目录
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 包有很多,如

  • flasgger
  • flask-swagger-ui
  • swagger-ui-py
  • ...

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

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

项目参考

  • Working with APIs using Flask, Flask-RESTPlus and Swagger UI
  • flask-restplus

--结束END--

本文标题: Flask 系列之 构建 Swagger

本文链接: https://www.lsjlt.com/news/182312.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Flask 系列之 构建 Swagger
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验 环境初始化 # 创建项目目录 mkdir helloworld cd helloworld ...
    99+
    2023-01-31
    系列之 Flask Swagger
  • Flask 系列之 优化项目结构
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 完善环境配置,添加 异常请求 处理 实现 400、404 和 500 处理 首先,在 t...
    99+
    2023-01-31
    结构 项目 系列之
  • Flask 系列之 Bootstrap-
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 通过使用 Bootstrap-Flask 来进行页面美化,为网站应用上 Bootstra...
    99+
    2023-01-31
    系列之 Flask Bootstrap
  • Flask 系列之 SQLAlchemy
    SQLAlchemy 是一种 ORM 框架,通过使用它,可以大大简化我们对数据库的操作,不用再写各种复杂的 sql语句 了。 说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv...
    99+
    2023-01-31
    系列之 Flask SQLAlchemy
  • Flask 系列之 Pagination
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 实现当前登录用户的事务浏览、添加、删除 操作 实现 首先,在我们的 todolist\f...
    99+
    2023-01-31
    系列之 Flask Pagination
  • Flask 系列之 Blueprint
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 学习如何使用 Blueprint 介绍 接触过 DotNet MVC 开发的朋友应该都对...
    99+
    2023-01-31
    系列之 Flask Blueprint
  • Flask 系列之 FlaskForm
    通过使用 FlaskForm ,可以方便快捷的实现表单处理。 说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 通过使用 flask_...
    99+
    2023-01-31
    系列之 Flask FlaskForm
  • Flask 系列之 LoginManag
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 通过使用 flask-login 进行会话管理的相关操作,并完成用户合法性登陆和退出。 ...
    99+
    2023-01-31
    系列之 Flask LoginManag
  • Flask 系列之 Migration
    说明 操作系统:Windows 10 Python 版本:3.7x 虚拟环境管理器:virtualenv 代码编辑器:VS Code 实验目标 通过使用 flask-migrate 实现数据库的迁移操作 实验 安装环境包 pip i...
    99+
    2023-01-31
    系列之 Flask Migration
  • Flask 扩展系列之 Flask-R
    简介 安装 快速入门 一个最小的 api 例子 资源丰富的路由 端点 参数解析 数据格式化 完整 TODO 应用例子 Flask-RESTful是一个Flask的扩展,它增加了对快速构建REST APIs的支持。它是一种轻...
    99+
    2023-01-31
    系列之 Flask
  • dockerfile构建flask环境
    简介 Dockerfile是一个文本格式的配置文件,用户可以使用Dockerfile快速创建自定义镜像 指令及说明 指令 说明 FROM 指定基础镜像 且必须是第一条指令 MAINTAINER 指定镜像作者 RUN 运...
    99+
    2023-01-31
    环境 dockerfile flask
  • Java 数据结构与算法系列精讲之队列
    目录概述队列队列实现enqueue 方法dequeue 方法main完整代码概述 从今天开始, 小白我将带大家开启 Jave 数据结构 & 算法的新篇章. 队列 队列 (Q...
    99+
    2024-04-02
  • 【windows Server 2019系列】 构建IIS服务器
    个人名片: 对人间的热爱与歌颂,可抵岁月冗长🌞 Github👨🏻‍💻:念舒_C.ying CSDN主页✏️:念舒_C.ying 个人...
    99+
    2023-09-07
    服务器 windows 前端
  • MAC+PyCharm+Flask+Vue.js搭建系统
    目录配置node.js+nvm+npmnpm切换淘宝镜像安装Vue.js创建并运行Vue.js项目在线初始化离线方式运行项目src文件以及作用解决打不开的问题配置Flask安装Fla...
    99+
    2024-04-02
  • JavaScript 数据结构之散列表的创建(2)
    目录一、处理散列值冲突1.分离链接2.put 方法3.get 方法前言: 上一篇我们介绍了什么是散列表,并且用通俗的语言解析了散列表的存储结构,最后动手实现了一个散列表,相...
    99+
    2024-04-02
  • JavaScript数据结构之散列表怎么创建
    本文小编为大家详细介绍“JavaScript数据结构之散列表怎么创建”,内容详细,步骤清晰,细节处理妥当,希望这篇“JavaScript数据结构之散列表怎么创建”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。一、处...
    99+
    2023-06-30
  • JavaScript 数据结构之散列表的创建(1)
    目录一、什么是散列表二、创建散列表1.创建散列函数2.put 方法3.get 方法4.delete 方法三、使用散列表四、总结上一篇我们一篇JavaScript 数据结构之...
    99+
    2024-04-02
  • Flask入门之完整项目搭建
      一、创建虚拟环境   1,新建虚拟环境   cmd中输入:mkvirtualenv 环境名   2,在虚拟环境安装项目运行所需要的基本模块 pip install flask==0.12.4 pip install redis pi...
    99+
    2023-01-31
    入门 完整 项目
  • Flask入门系列Cookie与session的介绍
    目录一、Cookie的使用1、什么是Cookie2、在Flask中使用Cookie二、session的使用1、什么是session2、Flask中的session对象3、在Flask...
    99+
    2024-04-02
  • ASP.Net Core MVC基础系列之项目创建
    一 : 系列教程环境介绍 1: 操作系统, Windows 10 专业版 64位 (版本号: 1809) 2: IDE使用Visual Studio 2017专业版 (版本号: 15...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作