了解python中的oauth2

时间:2018-05-09 00:51:05

标签: python api python-requests

我需要使用python访问API以从网站(API)接收一些数据,我以前从未这样做过,我学会了如何做,但我有文档http://developers.tray.com.br/

我不明白究竟什么是回调网址

我正在尝试生成要在应用程序中访问的密钥

PHP中的

示例是

?php
$params["consumer_key"] = "### Chave da Aplicação ###";
$params["consumer_secret"] = "### Chave Secreta da Aplicação ###";
$params["code"] = "### Código de Autorização ###";

$url = "https://{api_address}/auth/?".http_build_query($params);

ob_start();

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_exec($ch);

// JSON de retorno  
$resposta = json_decode(ob_get_contents());
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

ob_end_clean();
curl_close($ch);

if($code == "201"){
    //Tratamento dos dados de resposta da consulta.
}else{
    //Tratamento das mensagens de erro
}

>

我在python中尝试

import requests
from requests_oauthlib import OAuth1

link = 'https://www.URL/web_api/auth'


  consumer_key = 'MyConsumerKey'
  consumer_secret= 'MY Secret'

  app_code = 'APP Code'


  auth = OAuth1(consumer_key, consumer_secret)

  r = requests.get(link, auth=auth)

  print(r.status_code)

我的代码是返回错误400

我怎样才能在python中加入这个?

1 个答案:

答案 0 :(得分:0)

不使用ouath lib解决

import requests
import os
from requests_oauthlib import OAuth1

link = 'https://mylinkweb/web_api/auth'


consumer_key = 'key'         
consumer_secret= 'secret'

code = 'code'

payload = {'consumer_key' : consumer_key, 'consumer_secret' :  consumemer_secret, 'code' : code}
headers = {'Accept' : 'application/json'}


r = requests.post(link, json=payload, headers=headers)

r.status_code == 200
r_json = r.json()

print(r_json['acces_token')

所以打印了acces_token:D `