Python URLLib/URLLib2 POST [英] Python URLLib / URLLib2 POST

查看:37
本文介绍了Python URLLib/URLLib2 POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 wx/Python 创建一个超级简单的虚拟输入/输出板.对于我将要存储数据的服务器的请求之一,我已准备好以下代码:

I'm trying to create a super-simplistic Virtual In / Out Board using wx/Python. I've got the following code in place for one of my requests to the server where I'll be storing the data:

data = urllib.urlencode({'q': 'Status'})
u = urllib2.urlopen('http://myserver/inout-tracker', data)
for line in u.readlines():
  print line

没有什么特别的.我遇到的问题是,根据我阅读文档的方式,这应该执行发布请求,因为我已经提供了数据参数,而这并没有发生.我在该网址的索引中有此代码:

Nothing special going on there. The problem I'm having is that, based on how I read the docs, this should perform a Post Request because I've provided the data parameter and that's not happening. I have this code in the index for that url:

if (!isset($_POST['q'])) { die ('No action specified'); }
echo $_POST['q'];

每次运行 Python 应用程序时,我都会在控制台上打印未指定操作"文本.我将尝试使用请求对象来实现它,因为我已经看到了一些包含这些的演示,但我想知道是否有人可以帮助我解释为什么我没有收到带有此代码的发布请求.谢谢!

And every time I run my Python App I get the 'No action specified' text printed to my console. I'm going to try to implement it using the Request Objects as I've seen a few demos that include those, but I'm wondering if anyone can help me explain why I don't get a Post Request with this code. Thanks!

-- 已编辑--

此代码可以正常工作并正确发布到我的网页:

This code does work and Posts to my web page properly:

data = urllib.urlencode({'q': 'Status'})
h = httplib.HTTPConnection('myserver:8080')
headers = {"Content-type": "application/x-www-form-urlencoded", 
           "Accept": "text/plain"}
h.request('POST', '/inout-tracker/index.php', data, headers)
r = h.getresponse()
print r.read()

我仍然不确定为什么当我提供数据参数时 urllib2 库没有发布 - 对我来说,文档表明它应该发布.

I am still unsure why the urllib2 library doesn't Post when I provide the data parameter - to me the docs indicate that it should.

推荐答案

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

使用路径 /inout-tracker 而没有尾随 / 不会获取 index.php.相反,服务器将发出 302 重定向到带有尾随 / 的版本.

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

执行 302 通常会导致客户端将 POST 转换为 GET 请求.

Doing a 302 will typically cause clients to convert a POST to a GET request.

这篇关于Python URLLib/URLLib2 POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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