【问题标题】:How to rewrite this POST curl script in python?如何在 python 中重写这个 POST curl 脚本?
【发布时间】:2016-05-23 06:24:48
【问题描述】:

我打算用python重写这个POST请求:

<?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 属性。我可以用什么代替?

谢谢!

【问题讨论】:

  • 在python中使用requests

标签: php python post curl


【解决方案1】:

有很多python库可以使用:

http.client

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

请求

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

命令非常简单:

使用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)

上面提供的文档应该不难理解

【讨论】:

  • 您能否举一个使用这些库的发布请求示例?两个参数设置就够了。
猜你喜欢
  • 2015-10-21
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
相关资源
最近更新 更多