Python requests Session not passing cookies?

I have followed the documentation as far as I can tell, but it seems that the requests library Session object is not retaining cookies. Here is my simple code:

    with requests.Session() as s:
        url = '%s://'%http+serverStr+'/login/'
        s.get(url)
        payload = {'username': 'sfprod', 'password': <password>,
                   'csrfmiddlewaretoken': s.cookies['csrftoken'], 'next': '/'}
        login_resp = s.post(url, data=payload, headers=(dict(Referer=url)))

This is connecting to a Django server. When I run the first s.get() call I see these cookies returned:

<RequestsCookieJar[Cookie(version=0, name='csrftoken', value='Iw2k4RF5QIy6oNOA71681oq4kGVBxjzTmQCULicbWdr5ZfH1Kunrn30DNupQtFhF', port=None, port_specified=False, domain='gancho.local', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=True, expires=1761043315, discard=False, comment=None, comment_url=None, rest={'SameSite': 'Lax'}, rfc2109=False)]>

However when the second call happens, no cookies are passed to the server. The COOKIES member of the request object received is empty and the server returns 403 Forbidden. I stepped through the csrftoken code in the debugger and it is rejecting the request because the cookie is not present (to be precise, because there is no CSRF_COOKIE value in the META member of the request, but I assume this is because the cookie is not present).

I can log in with a browser, and in this case I see the cookie in the request, so I think it is not a setup problem with the server. Is there something I need to do with the session to get the cookie(s) to persist ?

Вернуться на верх