Hallöchen!

Larry Martell writes:

> I have a django view that normally receives POSTed data from a web
> page. That all works fine. But now we also want to call that view from
> a python script. That is failing with a 403 because of a CSRF
> mismatch. I can disable CSRF on my view and then it does work from the
> script.
>
> Is there some way I can have it work with CSRF with my script?

We make it like this (roughly, but you probably can fill the gaps
yourself):

class Connection(object):
    cookie_jar = cookiejar.CookieJar()
    opener = 
urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie_jar))
    http_headers = [("X-requested-with", "XMLHttpRequest"),
                    ("Accept", 
"application/json,text/html;q=0.9,application/xhtml+xml;q=0.9,text/*;q=0.8,*/*;q=0.7")]
    opener.addheaders = http_headers

    def do_http_request(self, url, data=None):
        if data is None:
            request = urllib.request.Request(url)
        else:
            # "Referer" is necessary for HTTPS communication.
            headers = {"Content-Type": "application/x-www-form-urlencoded", 
"Referer": url}
            request = urllib.request.Request(url, urllib.parse.urlencode(data), 
headers)
        self.opener.open(request)

    def set_csrf_header(self):
        """Copies the cookie to the header of the subsequent requests."""
        csrf_cookies = {cookie for cookie in cookie_jar if cookie.name == 
"csrftoken"}
        if csrf_cookies:
            assert len(csrf_cookies) == 1
            self.opener.addheaders = self.http_headers + [("X-CSRFToken", 
csrf_cookies.pop().value)]

    def login(self, username, password):
        # First, a GET request to get the CSRF cookie used only for the
        # following POST request.  (It's some sort of bootstrapping;
        # only necessary for the very first request.)
        self.do_http_request("http://mysite.com/login";)
        self.set_csrf_header()
        self.do_http_request("http://mysite.com/login";, {"username": username, 
"password": password})
        # Now, set the CSRF token for the rest of the communication.
        self.set_csrf_header()


Tschö,
Torsten.

-- 
Torsten Bronger    Jabber ID: torsten.bron...@jabber.rwth-aachen.de
                                  or http://bronger-jmp.appspot.com

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/87a92zle2u.fsf%40physik.rwth-aachen.de.
For more options, visit https://groups.google.com/d/optout.

Reply via email to