运行Locust时为什么会出现403错误?

时间:2014-12-03 00:11:15

标签: python django load-testing http-status-code-403 locust

我正在使用Locust(python)在Django Web应用程序上加载测试。我运行脚本时遇到403错误。

以下是代码:



  from locust import HttpLocust, TaskSet

def index(l):
    l.client.get("/")
def login(l):
    l.client.post("/login/", {"username":"an@id.com", "password":"education")
def upload(l):
    l.client.get("/upload-image/")
def home(l):
	 l.client.get("/home/")
def settings(l):
	l.client.get("/settings/")
def logout(l):
	l.client.get("/logout/")
class UserBehavior(TaskSet):
    tasks = {index:1, upload:1, home:1, settings:1, logout:1}

    def on_start(self):
        login(self)

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




2 个答案:

答案 0 :(得分:11)

要扩展ZacDelagrange的答案,当您使用https时,您还必须设置Referer标头,因此在此示例中您可以执行

def on_start(self):
    """ Run on start for every Locust hatched """
    r = self.client.get('')
    self.client.headers['Referer'] = self.client.base_url
    self.client.post('/accounts/login/', 
        {'email': 'email', 'password': 'password',
         'csrfmiddlewaretoken': r.cookies['csrftoken']})

答案 1 :(得分:8)

登录您的root或登录页面,从响应cookie中获取csrf令牌,然后使用csrftoken发布到您的登录URL。这应该将csrf令牌添加到客户端的cookie中,并允许您浏览该页面。

def on_start(self):
    """ Run on start for every Locust hatched """
    r = self.client.get('')
    self.client.post('/accounts/login/', 
        {'email': 'email', 'password': 'password',
         'csrfmiddlewaretoken': r.cookies['csrftoken']})