2016-05-23 49 views
1

我要去蟒蛇改寫這個POST請求:如何在python中重寫這個POST curl腳本?

<?php 
// Set these variables 
$networkid = ""; // In your HasOffers system at Support -> API 
$apikey = ""; // In your HasOffers system at Support -> API 
$offerid = "0"; // Specify an offer ID to add the creative to 
$creativetype = "image banner"; // Types: file, image banner, flash banner, email creative, offer thumbnail, text ad, html ad, hidden 
$filename = "banner_728x90.gif"; // File name; no spaces, and file must be in same directory as this script 
$display = $filename; // Or change this to the "display name" for this creative 

// Don't change anything below here 
$creativetype = urlencode($creativetype); 
$display = urlencode($display); 
$fields[$filename] = "@{$filename}"; 
$url = "http://api.hasoffers.com/v3/OfferFile.json?Method=create&NetworkToken={$apikey}&NetworkId={$networkid}&data[offer_id]={$offerid}&data[type]={$creativetype}&data[display]={$display}&return_object=1"; 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); 
$resp = curl_exec($ch); 
curl_close($ch); 

print_r(json_decode($resp, true)); // Final output; remove or change this if you want 
?> 

據我所知,在pycurl的CURLOPT_POSTFIELDS屬性不存在。我可以用什麼來代替?

謝謝!

+0

在python中使用'requests'。 – Daniel

回答

1

有可以使用的許多Python庫:

http.client

https://docs.python.org/3.1/library/http.client.html

請求

https://pypi.python.org/pypi/requests/

的命令是相當straightforwards:

使用http.client:

import http.client 
conn = http.client.HTTPConnection("www.python.org") 
conn.request("HEAD","/index.html") 
res = conn.getresponse() 
print(res.status, res.reason) 
200 OK 

或請求:

import requests 
r = requests.get('https://github.com/timeline.json') 
print r.json 

使用HTTP客戶機,一個簡單的POST請求可以如下進行:

connect = http.client.HTTPSConnection("base_url") 
connect.request('POST', '/rest/api/'+ you_can_add_variables+ '/users?userEmail=' + another_variable, headers=headers) 

使用請求:

import json 
url = 'https://api.github.com/some/endpoint' 
payload = {'some': 'data'} 
headers = {'content-type': 'application/json'} 

r = requests.post(url, data=json.dumps(payload), headers=headers) 

the doc以上提供的應用不應該難以理解

+0

你可以舉一個例子來說明使用這些庫的請求嗎?設置兩個參數是enogh。 – paus

+0

我編輯了我的評論 – glls