六、基于Flask、Flasgger、marshmallow的开发调试

news/2025/2/16 2:41:06/

基于Flask、Flasgger、marshmallow的开发调试

  • 问题描述
  • 调试方法一
  • 调试方法二
  • 调试方法三

问题描述

现在有一个传入传出为json格式文件的,Flask-restful开发的程序,需要解决如何调试的问题。

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Project    : combine all libraries examples.py
# @File    : RiGangTemplateTry.py
# @Time    : 2024/1/4 8:43
from flask import Flask, request
from flask_restful import Api, Resource
from flasgger import Swagger
from marshmallow import Schema, fields, ValidationError# 初始化 Flask 应用、API 和 Swagger
app = Flask(__name__)
api = Api(app)
swagger = Swagger(app)# 校验输入数据
class AgeSchema(Schema):name = fields.Str(required=True)age = fields.Integer(required=True)# 校验输出数据
class AgeStatSchema(Schema):average_age = fields.Float()max_age = fields.Integer()min_age = fields.Integer()class AgeStats(Resource):def post(self):"""Upload JSON and Calculate Age Stats---consumes:- application/jsonparameters:- in: bodyname: bodyschema:id: AgeInputtype: arrayitems:type: objectrequired:- name- ageproperties:name:type: stringage:type: integerdescription: JSON array with names and agesresponses:200:description: Age statisticsschema:id: AgeStatsproperties:average_age:type: numberformat: floatdescription: The average age of the submitted agesmax_age:type: integerdescription: The maximum age of the submitted agesmin_age:type: integerdescription: The minimum age of the submitted ages"""json_data = request.get_json()# 校验 JSON 数据try:results = AgeSchema(many=True).load(json_data)except ValidationError as err:return err.messages, 400# 计算平均年龄、最大年龄和最小年龄ages = [person['age'] for person in results]average_age = sum(ages) / len(ages)max_age = max(ages)min_age = min(ages)# 序列化输出数据stats_schema = AgeStatSchema()return stats_schema.dump({'average_age': average_age,'max_age': max_age,'min_age': min_age}), 200class UserSchema(Schema):username = fields.Str(required=True)email = fields.Email(required=True)class User(Resource):def get(self, username):"""Get User Endpoint---parameters:- in: pathname: usernametype: stringrequired: truedescription: The username of the userresponses:200:description: The user informationschema:id: UserResponseproperties:username:type: stringdescription: The username of the useremail:type: stringdescription: The email of the userexamples:application/json: { "username": "johndoe", "email": "john@example.com" }"""# 示例数据,实际应用中这里会是数据库查询等操作user_data = {"username": username, "email": f"{username}@example.com"}# 使用 Marshmallow Schema 校验和序列化数据user_schema = UserSchema()return user_schema.dump(user_data), 200api.add_resource(User, '/users/<string:username>')
api.add_resource(AgeStats, '/age_stats')if __name__ == '__main__':app.run(debug=True)

调试方法一

通过http://127.0.0.1:5000/apidocs/已经可以便捷的查看代码中的api数据。
在这里插入图片描述
但是在测试代码的时候仍然需要手动输入调试json数据在界面上
在这里插入图片描述

调试方法二

要使用您的Flask应用进行测试,您可以采用以下步骤:

  1. 确保您的环境已经安装了所有必需的库。如果还没有安装,您可以使用pip来安装它们:
pip install flask flask-restful flasgger marshmallow
  1. 保存并运行您的Flask应用。将您的脚本保存为一个.py文件,例如app.py,然后在命令行中运行它:
python app.py
  1. 准备您的测试数据。创建一个JSON文件data.json,包含您想要测试的数据,例如:
[{"name": "Alice", "age": 30},{"name": "Bob", "age": 25},{"name": "Charlie", "age": 35}
]
  1. 使用curl命令或者Postman等工具发送请求

使用curl发送POST请求:

curl -X POST -H "Content-Type: application/json" -d @data.json http://127.0.0.1:5000/age_stats

确保您的Flask应用正在运行,并且使用了data.json文件中的正确路径。

如果您更喜欢图形界面,可以使用Postman

  • 打开Postman。
  • 创建一个新的POST请求。
  • 在URL栏输入http://127.0.0.1:5000/age_stats
  • 在Headers部分,添加一个新的条目。对于key填入Content-Type,对于value填入application/json
  • 在Body部分,选择raw,然后从下拉菜单中选择JSON。
  • data.json文件中的数据复制并粘贴到raw文本区域中。
  • 点击Send。
  1. 观察响应。无论是curl还是Postman,您都应该收到一个包含平均年龄、最大年龄和最小年龄的JSON响应。

  2. 调试。如果测试没有按预期进行,您可以在Flask应用中添加print语句或使用Python的pdb模块来调试。您还可以检查Postman或终端中的错误信息来帮助诊断问题。

如果您遇到400 Bad Request错误,这通常意味着您的输入数据不符合AgeSchema的要求。在这种情况下,检查您的JSON数据确保每个对象都有nameage字段,并且age是一个整数。

在这里插入图片描述

调试方法三

写一个调试的脚本,使用Request调试

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Project    : combine all libraries examples.py
# @File    : TestRiGangTemplateTry.py
# @Time    : 2024/1/4 9:15import requests
import json# 设置您的API端点
url = 'http://127.0.0.1:5000/age_stats'# 准备您的测试数据
data = [{"name": "Alice", "age": 30},{"name": "Bob", "age": 25},{"name": "Charlie", "age": 35}
]# 将数据转换为JSON格式
json_data = json.dumps(data)# 发送POST请求
response = requests.post(url, data=json_data, headers={'Content-Type': 'application/json'})# 打印响应
print('Status Code:', response.status_code)
print('Response Body:', response.text)

在这里插入图片描述


http://www.ppmy.cn/news/1291981.html

相关文章

15 Linux 按键

一、Linux 按键驱动原理 其实案件驱动和 LED 驱动很相似&#xff0c;只不过区别在于&#xff0c;一个是读取GPIO高低电平&#xff0c;一个是从GPIO输出高低电平。 在驱动程序中使用一个整形变量来表示按键值&#xff0c;应用程序通过 read 函数来读取按键值&#xff0c;判断按键…

【docker】linux部署docker

简介 首先我需要声明的是&#xff0c;我的系统是centos7&#xff0c;下载工具使用的是yum&#xff1b;在linux上部署docker&#xff0c;之前一直看的是这篇文章Linux之Docker部署&#xff0c;基本上功能方面也都可以使用&#xff0c;部署起来也是比较的简单。首先我先讲述这篇…

【Android】如何设置应用程序启动Activity(应用启动时显示的界面)

前言 在Android中&#xff0c;AndroidManifest.xml文件可以通过修改来设置应用启动时显示的界面&#xff0c;即启动Activity。 操作步骤 打开AndroidManifest.xml文件。 在文件中找到想要设置为启动Activity的<activity>元素。该元素通常在<application>元素内部…

阿里云Alibaba Cloud Linux 2镜像操作系统版本大全

Alibaba Cloud Linux阿里云打造的Linux服务器操作系统发行版&#xff0c;Alibaba Cloud Linux完全兼容完全兼容CentOS/RHEL生态和操作方式&#xff0c;目前已经推出Alibaba Cloud Linux 3&#xff0c;阿里云百科aliyunbaike.com分享Alibaba Cloud Linux 2版本特性说明&#xff…

数字IC后端实现之快速获取innovus中drv violation的所有net list

在Innovus中place_opt_design和optDesign阶段&#xff0c;我们经常会看到如下所示的log提示信息&#xff0c;核心关键词是“ Reasons for remaining drv violations”。而且告诉我们总共有819条net存在drv violation&#xff0c;且无法被工具优化掉。 Reasons for remaining dr…

【网络】网络层IP地址和IP数据报的格式

&#x1f984; 个人主页——&#x1f390;开着拖拉机回家_Linux,大数据运维-CSDN博客 &#x1f390;✨&#x1f341; &#x1fa81;&#x1f341;&#x1fa81;&#x1f341;&#x1fa81;&#x1f341;&#x1fa81;&#x1f341; &#x1fa81;&#x1f341;&#x1fa81;&am…

【MATLAB】EEMD_LSTM神经网络时序预测算法

有意向获取代码&#xff0c;请转文末观看代码获取方式~也可转原文链接获取~ 1 基本定义 EEMD-LSTM神经网络时序预测算法是一种结合了扩展经验模态分解&#xff08;EEMD&#xff09;和长短期记忆神经网络&#xff08;LSTM&#xff09;的时间序列预测方法。 EEMD是一种改进的EM…

C++完成使用map Update数据

1、在LXMysql.h和LXMysql.cpp分别定义和编写关于pin语句的代码 //获取更新数据的sql语句 where语句中用户要包含where 更新std::string GetUpdatesql(XDATA kv, std::string table, std::string where); std::string LXMysql::GetUpdatesql(XDATA kv, std::string table, std…