How to close TCP connection in python locust (requests.session)

6/4/2020

I'm doing a load test with python Locust package on an service API that's running on Kubernetes.

I saw in the source code that the HttpUser uses requests.session.request() to send the requests. By default requests.session keeps the connection alive (which causes all the requests going to one pod instead of getting distributed across all pods on Kubernetes). Only way I know to close the connection after each request is setting connection: close when initializing the requests.session, which is abstracted away from me in Locust.

I tried adding headers={'connection':'close'} in the request call but that didn't do the trick. All requests still goes to the same pod. Anyone know how I can change this setting at runtime?

-- Xuekai Du
kubernetes
locust
python
python-requests
tcp

2 Answers

8/24/2020

You can try

request = requests.session.request()
request.close()
-- AMadKinnon
Source: StackOverflow

1/20/2021

Maybe you can also use User instead of HttpUser because HttpUser is thought to keep session betweek tasks.

using User instead of HttpUser you need to import requests and instance it, but it doesn't keep session by default. if you want to keep session create a session object and make calls with it.

for example

class Login(HttpUser)
    @task
    def activity():
        self.client.get('/url')

session betweek every run of this task id shared.

import requests

class Login(User)
    @task
    def activity():
        answer = requests.get('/')
        answer2 = requests.get('/')
        #answer and answer2 doesn't share session, every run of task doesn't share session
        session = requests.Session()
        answer3 = session.get('/')
        answer4 = session.get('/')
        #answer3 and 4 share same session, every run of task doesn't share session
-- Andrea Bisello
Source: StackOverflow