Python中的CURL POST

时间:2014-08-06 07:49:45

标签: python curl urllib2

我必须这样做,但不是使用PHP,而是使用 Python和Django ,而且我有点迷失。

<?php

$receiver_id = '<id de cobrador>';
$secret = '<llave de cobrador>';
$concatenated = "receiver_id=$receiver_id";
$hash = hash_hmac('sha256', $concatenated , $secret);

$url = 'https://khipu.com/api/1.3/receiverStatus';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);

$data = array('receiver_id' => $receiver_id, 'hash' => $hash);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

echo $output;

我认为它应该是urllib2,但我不确定其他的东西,如(curl_exec,curl_setopt ...)。

编辑:我这样做了

def pagar_khipu(request):
    receiver_id = '****';
    secret = '*******';
    concatenated = "receiver_id=%s" % receiver_id;
    hashed = hmac.new(secret, msg=concatenated, digestmod=hashlib.sha256).digest()

    url = 'https://khipu.com/api/1.3/receiverStatus';

    data = urllib.urlencode({'receiver_id': receiver_id, 'hash': hashed})
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)


    return HttpResponse(response)

并给我这个错误: 的 No exception message supplied

谢谢

2 个答案:

答案 0 :(得分:3)

我认为你不需要任何Django功能来实现这一目标。您可以查看&#34; requests&#34; Python中的库,并执行以下操作:

# -*- coding: utf-8 -*-
import requests, hmac, hashlib

receiver_id = '<id de cobrador>'
secret = '<llave de cobrador>'
concatenated = "receiver_id=" + receiver_id
hash = hmac.new(secret, concatenated, hashlib.sha256).hexdigest()
url = 'https://khipu.com/api/1.3/receiverStatus'
data = {
  'receiver_id' : receiver_id,
  'hash' : hash
}
req = requests.post(url, data=data)
print "Status code : " + str(req.status_code)
if req.text:
  print "Contents : " + str(req.text)

您可以使用 pip

安装请求模块
  

pip安装请求

答案 1 :(得分:1)

此网站上有很多关于此主题的类似问题。只需谷歌“python请求发布站点:stackoverflow.com”。

其他提示:您可能希望将Requests视为具有更现代化界面的库,而不是使用urllib。