使用python+flask设置挡板

在测试过程中,可能会需要使用挡板来模拟外部系统接口。比如涉及到外部系统接口调用时,可能会需要特定的返回,比如某个字段为指定值。或者在压测过程中,为了更准确的了解系统的性能,需要模拟外部系统的接口返回。

使用python+flask设置挡板,具体代码如下

```python

from flask import Flask, request

from xml.etree.ElementTree import fromstring, Element,SubElement,tostring

app = Flask(name)

@app.route('/directResponse', methods=['POST'])

def directResponse():

直接返回

response = {"status": 0, "message": "Success", "data": {"col1": "value1", "col2": "value2"}}

return response

@app.route('/baseOnRequest/response', methods=['POST'])

def baseOnRequest_response():

根据请求参数的不同,返回不同的响应

request_data = request.get_json() # 获取json格式的请求体

age = request_data.get('age')

name = request_data.get('name')

isadult = False

if int(age) >= 18:

isadult = True

response = {"status": 0, "message": "Success", "data": {"username": name, "isadult": isadult}}

return response

@app.route('/getMessage/<msg>', methods=['GET', 'POST'])

def getMessage(msg):

请求路径中带有参数的接口

userid = request.args.get('userid', default=None)

if None == userid:

return {"errorMessage": "用户id为空,请输入!"}

if msg == 'idcard':

response = {"status": 0, "message": "Success", "userid": userid, "idcard": "110110199901011234"}

elif msg == 'mobile':

response = {"status": 0, "message": "Success", "userid": userid,

"mobiles": [{"phoneNo": "13512341234"}, {"phoneNo": "13523452345"}]}

elif msg == 'name':

response = {"status": 0, "message": "Success", "userid": userid, "relname": "真实姓名"}

else:

response = {"status": -1, "message": "没有您要查询的信息", }

return response

@app.route('/xmlResponse',methods=['POST'])

def xmlResponse():

构建soup协议的XML响应

envelope = Element('soap:Envelope')

envelope.set('xmlns:soap','http:www.w3.org/2003/05/soap-envelope')

body = SubElement(envelope,'soap:Body')

response = SubElement(body,'xmlResponse')

response.set('xmlns','http://example.com/soap-service')

user = SubElement(response, 'user')

SubElement(user,'userid').text = '11111'

return tostring(envelope,encoding='unicode',xml_declaration=True)

if name == 'main':

app.run(host='127.0.0.1', port='8087', debug=True)

```

调用的结果分别如下

/directResponse

/baseOnRequest/response

/getMessage/<msg>

/xmlResponse

相关推荐
生信大表哥20 小时前
单细胞测序分析(五)降维聚类&数据整合
linux·python·聚类·数信院生信服务器
故事不长丨20 小时前
C#定时器与延时操作的使用
开发语言·c#·.net·线程·定时器·winform
hefaxiang20 小时前
C语言常见概念(下)
c语言·开发语言
欧阳天风20 小时前
js实现鼠标横向滚动
开发语言·前端·javascript
yue00821 小时前
C# Directory的用法介绍
开发语言·c#
seeyoutlb21 小时前
微服务全局日志处理
java·python·微服务
ada7_21 小时前
LeetCode(python)——148.排序链表
python·算法·leetcode·链表
雨落秋垣21 小时前
手搓 Java 的用户行为跟踪系统
java·开发语言·linq
岁月宁静1 天前
LangChain + LangGraph 实战:构建生产级多模态 WorkflowAgent 的完整指南
人工智能·python·agent
爱丽_1 天前
深入理解 Java Socket 编程与线程池:从阻塞 I/O 到高并发处理
java·开发语言