Python URLLib / URLLib2 POST
我正在尝试使用 wx/Python 创建一个超级简单的虚拟输入/输出板。我已经为我将存储数据的服务器请求之一准备了以下代码:
data = urllib.urlencode({'q': 'Status'})
u = urllib2.urlopen('http://myserver/inout-tracker', data)
for line in u.readlines():
print line
那里没有什么特别的事情发生。我遇到的问题是,根据我阅读文档的方式,这应该执行发布请求,因为我已经提供了数据参数,但这种情况没有发生。我在该 url 的索引中包含以下代码:
if (!isset($_POST['q'])) { die ('No action specified'); }
echo $_POST['q'];
每次运行 Python 应用程序时,控制台都会打印“未指定操作”文本。我将尝试使用请求对象来实现它,因为我已经看到了一些包含这些对象的演示,但我想知道是否有人可以帮助我解释为什么我没有使用此代码收到发布请求。谢谢!
-- 编辑 --
这段代码确实有效,并且可以正确发布到我的网页:
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'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'];
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!
-- EDITED --
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()
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用没有尾随
/
的路径/inout-tracker
不会获取index.php
。相反,服务器将发出302
重定向到尾随/
的版本。执行 302 通常会导致客户端将 POST 请求转换为 GET 请求。
Using the path
/inout-tracker
without a trailing/
doesn't fetchindex.php
. Instead the server will issue a302
redirect to the version with the trailing/
.Doing a 302 will typically cause clients to convert a POST to a GET request.