Going off of this other SO question, I tried to use urlencode and urlopen to POST data to a form. However, Django 1.2 gives me a CSRF verification failed error when I use it. Is there a workaround?
Thanks.
The Python 3 standard library has a new urllib which is a merged/refactored/rewritten version of the older modules. urllib3 is a third-party package (i.e., not in CPython's standard library).
Urllib package is the URL handling module for python. It is used to fetch URLs (Uniform Resource Locators). It uses the urlopen function and is able to fetch URLs using a variety of different protocols.
You need to use from urllib. request import urlopen , also I suggest you use the with statement while opening a connection. @BradleyD. Freeman-Bain: you can't have a with -statement without the following block.
urllib2 is a Python module that can be used for fetching URLs. It defines functions and classes to help with URL actions (basic and digest. authentication, redirections, cookies, etc) The magic starts with importing the urllib2 module.
The difference between submitting data to other forms and your case is that you will have to first get the CSRF token. This can be done by performing a GET request on the page first and then parsing the csrfmiddlewaretoken
using a suitable parser.
Also keep in mind that you'll need to install a cookie jar to get this to work.
For example:
#!/usr/bin/python
import urllib, urllib2, cookielib
from BeautifulSoup import BeautifulSoup
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
url = urllib2.urlopen('http://localhost:8000/accounts/login/')
html = url.read()
doc = BeautifulSoup(html)
csrf_input = doc.find(attrs = dict(name = 'csrfmiddlewaretoken'))
csrf_token = csrf_input['value']
params = urllib.urlencode(dict(username = 'foo', password='top_secret',
csrfmiddlewaretoken = csrf_token))
url = urllib2.urlopen('http://localhost:8000/accounts/login/', params)
print url.read()
use the csrf_exempt decorator for the view that is handling the request
from django.views.decorators.csrf import csrf_exempt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With