请问为什么我对这个帖子的电话请求不好?它与json格式有关。如何重新格式化作为参数传递的json对象?我正在使用LocustIO,python
运行负载测试 from locust import HttpLocust, TaskSet, task
from slumber import API
import json, requests
nameInquiry = """
[{
"data": {
"Account Number": "1234567898",
"Bank Code": "EBN",
"AppId": "com.appzonegroup.zone",
"deviceId": "a4a7427032c286e3",
"Sender Phone Number": "+2348094399450",
"Sender Conversation ID": "161503479186618e8726fc4-70c0-4768-a2ea-5217c3a3c26d",
"FileId": ""
},
"instruction": {
"FunctionId": "",
"FlowId": "813dac4f-7e44-4873-b45f-f6f3b5dbe436",
"InstitutionCode": "",
"TimeOutSeconds": 30
}
}]
"""
myheaders = {'Content-Type': 'application/json', 'Accept': 'application/json'}
class NameInquiries(TaskSet):
@task(1)
def send(self):
response = self.client.post("/zoneflowsapi/api/Goto/goto/", data=json.dumps(nameInquiry), headers= myheaders )
print("Response status code:", response.status_code)
print("Response content:", response.text)
答案 0 :(得分:1)
json.dumps将json对象(列表和字典)作为输入,并将其序列化,并将字符串作为输出。你用nameInquiry
喂它,它本身就是一个字符串,因此是错误。
此外post获取字典作为输入,因此无需序列化它。简单的解决方案是将nameInquiry
设置为json对象(注意下面缺少的"""
)并直接将其提供给post。
nameInquiry = [{
"data": {
"Account Number": "1234567898",
"Bank Code": "EBN",
"AppId": "com.appzonegroup.zone",
...
}]
...
response = self.client.post("/zoneflowsapi/api/Goto/goto/", data=nameInquiry, headers=myheaders)
否则,您可以使用json.loads保留字符串并对其进行反序列化:
nameInquiry = json.loads("""
[{
"data": {
"Account Number": "1234567898",...
""")
答案 1 :(得分:0)
有两种使用Locust发布JSON数据的常规方法。我更喜欢将字典传递给self.client.post
using the json keyword argument,因为我不必担心创建有效的JSON:
nameInquiry = [{
"data": {
"Account Number": "1234567898",
"Bank Code": "EBN",
"AppId": "com.appzonegroup.zone",
"deviceId": "a4a7427032c286e3",
"Sender Phone Number": "+2348094399450",
"Sender Conversation ID": "161503479186618e8726fc4-70c0-4768-a2ea-5217c3a3c26d",
"FileId": ""
},
...
}]
response = self.client.post("/zoneflowsapi/api/Goto/goto/", json=nameInquiry)
另一种方法是手动创建有效的JSON字符串,或使用json.dumps(dict)
创建有效的JSON字符串,然后使用self.client.post
参数将字符串传递给data
:>
nameInquiryString = """
[{
"data": {
"Account Number": "1234567898",
"Bank Code": "EBN",
"AppId": "com.appzonegroup.zone",
"deviceId": "a4a7427032c286e3",
"Sender Phone Number": "+2348094399450",
"Sender Conversation ID": "161503479186618e8726fc4-70c0-4768-a2ea-5217c3a3c26d",
"FileId": ""
}
...
}]
"""
response = self.client.post("/zoneflowsapi/api/Goto/goto/", data=nameInquiryString)
如果您使用的是self.client.put
,则必须使用第二种方法,因为put
方法不支持json
关键字参数。