简体   繁体   English

使用 Locust 获取响应数据的问题

[英]Issue with getting the response data using Locust

Im trying to see if I'm able to get the response data as I'm trying to learn how to use regex on Locust.我想看看我是否能够获得响应数据,因为我正在尝试学习如何在 Locust 上使用正则表达式。 I'm trying to reproduce my test script from JMeter using Locust.我正在尝试使用 Locust 从 JMeter 重现我的测试脚本。 This is the part of the code that I'm having problem with.这是我遇到问题的代码部分。

import time,csv,json
from locust import HttpUser, task,between,tag

class ResponseGet(HttpUser):
    response_data= ""
    wait_time= between (1,1.5)
    host= "https://portal.com"
    username= "NA"
    password= "NA"

    @task
    def portal(self):
        print("Portal Task")
        response = self.client.post('/login', json={'username':'user','password':'123'})
        print(response)
        self.response_data = json.loads(response.text)
        print(response_data)     

I've tried this suggestion and I somehow can't make it work. 我已经尝试过这个建议,但不知何故无法让它发挥作用。

My idea is get response data > use regex to extract string > pass the string for the next task to use我的想法是获取响应数据 > 使用正则表达式提取字符串 > 传递字符串以供下一个任务使用

For example: Get login response data > use regex to extract token > use the token for the next task.例如:获取登录响应数据 > 使用正则表达式提取令牌 > 将令牌用于下一个任务。

Is there any better way to do this?有没有更好的方法来做到这一点?

The way you're doing it should work, but Locust's HttpUser's client is based on Requests so if you want to access the response data as a JSON you should be able to do that with just self.response_data = response.json() .你这样做的方式应该可行,但 Locust 的 HttpUser 客户端基于请求,所以如果你想以 JSON 形式访问响应数据,你应该能够只使用self.response_data = response.json()来做到这一点。 But that will only work if the response body is valid JSON.但这只有在响应正文是有效的 JSON 时才有效。 Your code will also fail if the response body is not JSON.如果响应正文不是 JSON,您的代码也会失败。

If your problem is in parsing the response text as JSON, it's likely that the response just isn't JSON, possibly because you're getting an error or something.如果您的问题是将响应文本解析为 JSON,则响应可能不是 JSON,可能是因为您收到错误或其他原因。 You could print the response body before your attempt to load it as JSON.您可以在尝试将其加载为 JSON 之前打印响应正文。 But your current print(response) won't do that because it will just be printing the Response object returned by Requests.但是您当前的print(response)不会这样做,因为它只会打印 Requests 返回的Response对象。 You'd need to print(response.text()) instead.您需要改为print(response.text())

As far as whether a regex would be the right solution for getting at the token returned in the response, that will depend on how exactly the response is formatted.至于正则表达式是否是获取响应中返回的令牌的正确解决方案,这将取决于响应的确切格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM