代码之家  ›  专栏  ›  技术社区  ›  Akshay Maldhure

回答status\u代码为200,但响应为。内容为空

  •  1
  • Akshay Maldhure  · 技术社区  · 7 年前

    我正在使用Locust对一些API进行负载测试,下面是Locust文件(locastfile.py)的样子:

    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
    

    以下是我触发测试的方式:

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

    问题是,在日志中, response.status_code 打印为200,但 response.content 正好是空的。当我使用Postman访问相同的API时,我在响应中看到了预期的正确响应主体。这看起来像是一个奇怪的问题,它阻止我调用另一个依赖于 get_something() 方法,因为其他API从 get\u something() 方法作为输入。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Corey Goldberg    7 年前

    Locust的默认HTTP客户端是Requests。

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

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

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