response.status_code is 200, but response.content is empty

时间:2017-12-18 06:08:31

标签: python locust

I'm working with Locust for load testing a few APIs, below is what the locust file (locustfile.py) looks like:

class MyTests(TaskSet):

def on_start(self):
    print("Starting tests")

def get_something(self):
    with self.client.get("some_baseuri" + "some_basepath", catch_response=True) as response:
        print("Response code: {}".format(response.status_code))
        print("Response body: {}".format(response.content))

@task(1)
def my_task(self):
    self.get_something()


class WebsiteUser(HttpLocust):
    task_set = MyTests

Here's how I trigger my tests:

locust -f locustfile.py --no-web --clients=1 --hatch-rate=10 --host=http://127.0.0.1 --num-request=2 --print-stats --only-summary

The problem is, in logs, response.status_code is printed as 200, but response.content happens to be empty. When I hit the same API using Postman, I see a proper response body in the response as expected. This looks like a strange issue which blocks me from calling another API which is dependent on the get_something() method since the other API takes some data from get_something() method as an input.

2 个答案:

答案 0 :(得分:2)

Locust的默认HTTP客户端是请求。

请求为您提供了几种访问响应内容的方法:

  • 将内容解码为纯文本,请使用response.text
  • 用于将内容解码为json,请使用response.json()
  • 用于以二进制数据的形式访问内容,请使用response.content
  • 对于原始套接字响应,请使用response.raw

请求文档的“响应内容”部分详细解释了这一点:http://docs.python-requests.org/en/master/user/quickstart/#response-content

答案 1 :(得分:0)

response.text or response._content instead of response.content worked.