def get_csrf_token ( response ) : cookie_headers = [ h . decode ( 'ascii' ) for h in response . headers . getlist ( "Set-Cookie" ) ] if not cookie_headers : return None csrf_headers = [ h for h in cookie_headers if h . startswith ( "csrftoken=" ) ] if not csrf_headers : return None match = re . match ( "csrftoken=([^ ;]+);" , csrf_headers [ - 1 ] ) return match . group ( 1 )
python how to get a csrf token from a response object
Extract the CSRF token out of the Set - Cookie header of a response .
def get_csrf_token(response):
    """
    Extract the CSRF token out of the "Set-Cookie" header of a response.
    """
    cookie_headers = [
        h.decode('ascii') for h in response.headers.getlist("Set-Cookie")
    ]
    if not cookie_headers:
        return None
    csrf_headers = [
        h for h in cookie_headers if h.startswith("csrftoken=")
    ]
    if not csrf_headers:
        return None
    match = re.match("csrftoken=([^ ;]+);", csrf_headers[-1])
    return match.group(1)