无法让Python 3将POST数据传输到PHP

时间:2012-09-30 23:02:45

标签: php python http post urllib

我想从Python 3向PHP站点发送一个简单的字符串,将其转换为.txt文件。我的整个代码如下所示:

的Python:

import urllib.parse
import urllib.request

str1 = "abcdefg"

url = "http://site.net/post.php"

aa = str1.encode('utf-8')
req = urllib.request.Request(url, aa)
req.add_header('Content-Type', 'this/that')
urllib.request.urlopen(req, data=aa)

PHP:

<?php

$handle = fopen("/dir/".name.".txt", "w");

$myContent = $_POST[aa];

fwrite($handle, $myContent);

fclose($handle);

?>

Python访问该站点,并创建.txt文件,但文件为空。我尝试将$_POST更改为$_GET$_REQUEST,并在'aa'周围的不同位置放置单引号和双引号。我怀疑PythonPHP没有就我希望它解释的字符串/数据的名称进行沟通。

  

编辑:此PHP代码已经处理来自其他网站的POST数据。这个问题只出现在Python兼容性

3 个答案:

答案 0 :(得分:2)

您的数据需要像哈希一样:

a = {}
a["name"] = "ben";

然后你需要在它上面调用urllib.urlencode

a = urllib.urlencode(a)

然后像这样调用urlopen:

urllib.request.urlopen(req, a)

答案 1 :(得分:1)

您可以使用file_put_contents使用$_POST[aa]无效,$_POST['aa']

$file = "/dir/".name.".txt" ;
file_put_contents($file, $_POST['aa']);

我认为你应该看看httplib2

from httplib2 import Http
from urllib import urlencode
h = Http()
str1 = body = {'aa': 'abcdefg'}
resp, content = h.request("http://site.net/post.php", "POST", urlencode(data))

答案 2 :(得分:1)

您发送的数据无效。关注the documentation

  

data 应该是标准application / x-www-form-urlencoded格式的缓冲区。 urllib.parse.urlencode()函数采用2元组的映射或序列,并以此格式返回一个字符串。 在用作数据参数之前,应将其编码为字节。

该文档还包含您需要遵循的simple example

import urllib.request
import urllib.parse

data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
data = data.encode('utf-8')
request = urllib.request.Request("http://requestb.in/xrbl82xr")

# adding charset parameter to the Content-Type header.
request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")

f = urllib.request.urlopen(request, data)
print(f.read().decode('utf-8'))