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

相关推荐
兵慌码乱2 小时前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei5 小时前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi0011 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn12 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵2 天前
用 Python 实现 Take-Away 游戏
python·游戏