djangosessionidlocust

Django sessionid not created for Locust client


I'm running Django 2.2.24 and Locust 2.1.0 for load testing. When I run some Locust test logging in as a the Django admin user, there are no issues - all my GETs work as expected.

Now I am actually logging in as a specific user. From a web interface, Django passes a CSRFtoken and a sessionid token with no problem. From the Locust client however, the sessionid does not show up at all. Not only that, but when I look in the django_session table (where the web tokens do exist), there are no tokens for the Locust client.

I think this is more related to Django session management than to locust - hence the post in this forum.

My locust file looks like this:

def on_start(self):
    '''
    The start script for each user - this order is important
    '''
    # Below 3 lines work fine - we get the csrftoken and put it in the header successfully
    response = self.client.get("/accounts/login")
    self.csrftoken = response.cookies['csrftoken']
    self.headers = {'X-CSRFToken': self.csrftoken}

    # Now login with username and password as POST
    r1 = self.login()
    return r1

def login(self):
    # admin login  and retrieving it's access token
    
    udata = {'username': self.username, 'password': self.password}
    cookies=self.client.cookies.get_dict())
    #csrftoken cookie does exist, sessionid does not yet.
    log.info("Current cookies in Login:" + str(self.client.cookies))
    # This next line should come back with a sessionid 
    # from Django - but it does not.
    response = self.client.post("/accounts/login/",
                                data=json.dumps(udata),
                                headers=self.headers)
    log.info("Response from client.post="+str(response)) #OK
    log.info("Response status code:" + str(response.status_code))
    log.info("Response text=" + response.text)
    # Next line does not contain sessionid or Set-Cookie 
    log.info("Headers from post/accts/login = " + str(response.headers)) 

Thanks for any assistance.


Solution

  • Change

    response = self.client.post("/accounts/login/",
                                data=json.dumps(udata),
                                headers=self.headers)
    

    to

    response = self.client.post("/accounts/login/",
                                json=udata,
                                headers=self.headers) 
    

    … to get the appropriate json headers. Or use:

    response = self.client.post("/accounts/login/",
                                data=udata,
                                headers=self.headers)
    

    in order to send it as form-encoded data instead of json.