Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Load testing using locust giving Csrf token error

I am writing a script for load testing for my django application , but I am getting error as :

raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='csrftoken', domain=None, path=None"

Here is my script:

from locust import HttpLocust, TaskSet, task
import requests

class UserBehavior(TaskSet):
    def on_start(self):
        """ on_start is called when a Locust start before any task is scheduled """
        self.login()

    def login(self):
        response = self.client.get("/")
        csrftoken = response.cookies['csrftoken']
        self.client.post('/check_login/',{'username': '####', 'password': '########'},headers={'X-CSRFToken': csrftoken})


    @task(2)
    def index(self):
        self.client.get("/")

    @task(1)
    def profile(self):
        self.client.get("/home")

class WebsiteUser(HttpLocust):
    task_set = UserBehavior
    min_wait = 5000
    max_wait = 9000

In command Line ,I am giving this command to start locust : locust --host=http://localhost:8080

Any suggestions on how to rectify this error ?

like image 799
Nishant Kumar Avatar asked Sep 17 '25 16:09

Nishant Kumar


1 Answers

There are two requirements for this to work:

  1. csrftoken should be passed inside the form data as csrfmiddlewaretoken.
  2. Along with X-CSRFToken header, Referer header is also required.

The code would then look like:

self.client.post(
    '/check_login/',
    {
        'username': '####',
        'password': '########',
        'csrfmiddlewaretoken': csrftoken
    },
    headers={
        'X-CSRFToken': csrftoken,
        'Referer': self.parent.host + '/check_login/'
    })
like image 140
philoj Avatar answered Sep 22 '25 11:09

philoj