使用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

相关推荐
程序员爱钓鱼几秒前
Python编程实战 · 基础入门篇 | Python的缩进与代码块
后端·python
earthzhang20211 小时前
【1028】字符菱形
c语言·开发语言·数据结构·c++·算法·青少年编程
pr_note1 小时前
python|if判断语法对比
python
earthzhang20213 小时前
第3讲:Go垃圾回收机制与性能优化
开发语言·jvm·数据结构·后端·性能优化·golang
apocelipes3 小时前
golang unique包和字符串内部化
java·python·性能优化·golang
纵有疾風起4 小时前
C++——类和对象(3)
开发语言·c++·经验分享·开源
Geoking.4 小时前
NumPy zeros() 函数详解
python·numpy
Full Stack Developme4 小时前
java.text 包详解
java·开发语言·python
文火冰糖的硅基工坊4 小时前
[嵌入式系统-135]:主流AIOT智能体开发板
开发语言·嵌入式·cpu
丁浩6665 小时前
Python机器学习---2.算法:逻辑回归
python·算法·机器学习