urllib2:提交表单然后重定向 [英] urllib2: submitting a form and then redirecting

查看:116
本文介绍了urllib2:提交表单然后重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是想出一个可移植的urllib2解决方案,它将发布一个表单,然后将用户重定向到出现的问题。
POSTing部分很简单:

  request = urllib2.Request('https://some.site/page ',data = urllib.urlencode({'key':'value'}))
response = urllib2.urlopen(request)

提供 data 将请求类型设置为POST。现在,我怀疑我应该关心的所有数据来自 response.info()& response.geturl()。我应该在 get(self)方法中使用 self.redirect(response.geturl()) c $ c> webapp.RequestHandler 。



但是我应该如何处理标题?还有什么我忽略了?代码片段受到高度赞赏。 :)

TIA。



编辑:这是我想出的一种天真的解决方案。重定向但远程服务器显示一个错误,指示与先前的POST表单不匹配:

  info = response.info() 
用于键入信息:
self.response.headers [key] = info [key]
self.response.headers ['Location'] = response.geturl()
self.response.set_status(302)
self.response.clear()


解决方案

我怀疑这几乎总是会失败。当您发布表单时,您最终得到的网址就是您发布的网址。发送其他人到这个URL,或者甚至用刚刚发布的同一个浏览器再次访问它,将会进行一次GET,并且该页面将没有被发布的表单数据。唯一的办法是,如果网站在POST后重定向到包含某种会话信息的URL。


My goal is to come up with a portable urllib2 solution that would POST a form and then redirect the user to what comes out. The POSTing part is simple:

request = urllib2.Request('https://some.site/page', data=urllib.urlencode({'key':'value'}))
response = urllib2.urlopen(request)

Providing data sets request type to POST. Now, what I suspect all the data I should care about comes from response.info() & response.geturl(). I should do a self.redirect(response.geturl()) inside a get(self) method of webapp.RequestHandler.

But what should I do with headers? Anything else I've overlooked? Code snippets are highly appreciated. :)

TIA.

EDIT: Here's a naive solution I came up with. Redirects but the remote server shows an error indicating that there's no match to the previously POSTed form:

info = response.info()
for key in info:
    self.response.headers[key] = info[key]
self.response.headers['Location'] = response.geturl()
self.response.set_status(302)
self.response.clear()

解决方案

I suspect this will almost always fail. When you POST a form, the URL you end up at is just the URL you posted to. Sending someone else to this URL, or even visiting it again with the same browser that just POSTed, is going to do a GET and the page won't have the form data that was POSTed. The only way this would work is if the site redirected after the POST to a URL containing some sort of session info.

这篇关于urllib2:提交表单然后重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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