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 w开发者_开发百科orkaround?
Thanks.
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
精彩评论