2012-09-30 26 views
1

我想從Python 3發送一個簡單的字符串到PHP網站,該網站將其轉換爲.txt文件。我的整個代碼如下所示:無法讓Python 3將POST數據傳輸到PHP

的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數據。

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

,那麼你需要調用它的urllib.urlencode

a = urllib.urlencode(a) 

然後調用的urlopen這樣的:這個問題只能用Python的兼容性

+0

我應該指出,這個PHP代碼已經從其他網站處理POST數據。該問題僅出現在Python兼容性上。 – tqastro

回答

1

你發送的數據是無效的。以下the documentation

數據應在標準應用程序/ 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')) 
+0

我不知道我的數據需要在{: }表單。我也認爲data.encode和.urlencode是多餘的,但是在後面的data.encode後面對dict對象執行後者。做只data.encode沒有註冊,因爲它只是一個str對象,但沒有錯誤,因爲數據是utf8格式。另外,我忽略了標題,因爲我不認爲這是必要的。如果我想要,我可以改變多少? – tqastro

2

您的數據需要一個散列出現像這個:

urllib.request.urlopen(req, a) 
+0

仍然收到TypeError消息。 urlencode似乎沒有將數據轉換爲utf8字節。到目前爲止,我的上面的代碼: aa = str1.encode('utf-8') 是唯一將其轉換爲適當格式的代碼,除了PHP似乎忽略它(但沒有錯誤)。 – tqastro

+0

@tqastro:不,它不是一個合適的格式,因爲你得到的字節序列不包含'=',所以它不能成爲有效的POST數據。 – lqc

1

你可以用use 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)) 
+0

寫上「POST」會讓我覺得我把它作爲我的數據發送,而且它是錯誤的。另外,你是說使用urllib。** parse **。urlencode?這似乎沒有正確編碼,因爲我收到一個關於需要字節而不是字符串的TypeError。 – tqastro

+0

查看更新代碼忘記告訴你我正在使用'httplib2'查看一些詳細示例http://code.google.com/p/httplib2/wiki/Examples – Baba