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

相关推荐
名字还没想好☜10 分钟前
Python concurrent.futures 实战:用 ThreadPoolExecutor 并发处理 + as_completed 收结果
数据库·python·php·并发
爱码小白17 分钟前
importlib模块
开发语言·前端·python
axinawang34 分钟前
第25课 for循环的应用
python
逻极1 小时前
FastAPI 实战:从入门到自动化文档,如何把API开发效率提升200%
python·api·fastapi·swagger·异步
techdashen1 小时前
Go设计取舍之四: map不变时能否并发修改不同value
开发语言·后端·golang
小小小米粒1 小时前
阿姆达尔定律(Amdahl‘s Law)
java·开发语言
知彼解己1 小时前
Java 版本演进
java·开发语言·spring boot
风样滴男人哟1 小时前
PHP特性之反射类ReflectionClass机制
android·开发语言·php
半兽先生1 小时前
大模型技术开发与应用——5.大模型Agent开发(CrewAI)
大数据·人工智能·python·机器学习·ai
眼泪划过的星空1 小时前
快速了解LangGraph:构建智能Agent工作流的核心框架
人工智能·python·langchain