如何使用urllib发布到Django 1.2表单? [英] How do I post to a Django 1.2 form using urllib?

查看:125
本文介绍了如何使用urllib发布到Django 1.2表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

退出其他SO问题,我尝试使用urlencode和urlopen将数据POST到表单。但是,Django 1.2给我一个CSRF验证失败的错误,当我使用它。有没有解决方法?

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?

谢谢。

推荐答案

将数据提交给其他表单,您的情况是您必须先获取CSRF令牌。这可以通过首先在页面上执行GET请求,然后使用合适的解析器解析 csrfmiddlewaretoken 来完成。

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.

还请记住,您需要安装一个cookie jar才能使其工作。

Also keep in mind that you'll need to install a cookie jar to get this to work.

例如:

#!/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()

这篇关于如何使用urllib发布到Django 1.2表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆