Locust中FastHTTPUser发起请求前配置硬编码JSON格式Cookie的方法
The key issue here is that FastHTTPUser uses a different underlying HTTP client (geventhttpclient) compared to HTTPUser (which relies on requests), so the cookies parameter syntax you’re used to won’t work directly. Here are two reliable, practical methods to set hardcoded cookies with FastHTTPUser:
Method 1: Manually Construct the Cookie Header (for one-off requests)
Since cookies are transmitted via the Cookie HTTP header, you can build the header string yourself and include it in your request headers. This is ideal if you only need cookies for a single request.
from locust import task, FastHTTPUser class LoadTestUser(FastHTTPUser): @task def send_post_request(self): # Define your cookies as a key-value dict my_cookies = { "session_id": "my-hardcoded-session-123", "user_auth_token": "xyz-abc-789" } # Convert the dict to a valid Cookie header string cookie_header = "; ".join([f"{key}={value}" for key, value in my_cookies.items()]) # Build your request headers (include the Cookie header) request_headers = { "Content-Type": "application/json", "Cookie": cookie_header } # Your POST payload post_payload = {"action": "submit", "data": "test-content"} # Send the POST request response = self.client.post( url="/api/submit", json=post_payload, headers=request_headers )
Method 2: Persist Cookies to the Client (for all user requests)
If you want the cookies to be automatically included in every request made by the user, you can populate the FastHTTPUser client’s cookies attribute (a SimpleCookie object) during the user’s initialization phase.
from locust import task, FastHTTPUser from http.cookies import SimpleCookie class LoadTestUser(FastHTTPUser): def on_start(self): # Runs once when the user starts (perfect for setup tasks) user_cookies = SimpleCookie() # Add your hardcoded cookie pairs user_cookies["session_id"] = "my-hardcoded-session-123" user_cookies["user_auth_token"] = "xyz-abc-789" # Attach the cookies to the client—they'll be sent with all subsequent requests self.client.cookies.update(user_cookies) @task def send_post_request(self): post_payload = {"action": "submit", "data": "test-content"} # No need to specify cookies here—they're automatically included response = self.client.post( url="/api/submit", json=post_payload )
Key Notes:
- FastHTTPUser’s client does not support the
cookiesparameter that HTTPUser (requests-based) uses, so you can’t pass a dict directly topost()orget()like you did before. - For dynamic cookies (e.g., retrieved from a login response), you can extract the
Set-Cookieheader from the login response and add it to the client’s cookies using the sameSimpleCookieapproach.
内容的提问来源于stack exchange,提问作者vnbal




