使用Python替代CURL/Ruby从API获取数据

0 投票
2 回答
1219 浏览
提问于 2025-04-16 11:55

我想用Python从一个API获取数据。这个API的文档里给了CURL和Ruby的例子。如果你能发一些Python的代码片段,教我怎么做以下事情,我会非常开心。

首先是获取认证令牌:

Curl的例子:

curl -X POST -d "{\"username\" : \"user@sample.com\", \"password\":\"sample\"}" http://api.sample.com/authenticate

Ruby的例子:

require 'rubygems'
require 'rest_client'
require 'json'

class AuthorizationClient
  attr_accessor :base_url

  def initialize(base_url)
    @base_url = base_url
  end

  def authenticate(username,password)
    login_data = { 'username' => username, 'password' => password}.to_json
    begin
      JSON.parse(RestClient.post "#{@base_url}/authenticate", login_data, :content_type => :json, :accept => :json)['output']
    rescue Exception => e
      JSON.pretty_generate JSON.parse e.http_body
    end
  end
end

client = AuthorizationClient.new('http://api.sample.com/authenticate')
puts client.authenticate('user@sample.com','sample')

认证之后,怎么获取数据:

CURL的例子:

curl http://api.sample.com/data/day/2011-02-10/authToken/80afa08-1254-46ee-9545-afasfa4565

还有Ruby的代码:

require 'rubygems'
require 'rest_client'
require 'json'

class ReportingClient
  attr_accessor :auth_token, :base_url

  def initialize(base_url)
    @base_url = base_url
  end

  def authenticate(username,password)
    login_data = { 'username' => username, 'password' => password}.to_json

    response = RestClient.post "#{@base_url}/authenticate", login_data, :content_type => :json, :accept => :json
    @auth_token = JSON.parse(response)['output']
  end

  def get_report(start_date, end_date)
    response = RestClient.get "#{@base_url}/data/day/#{day}/authToken/#{auth_token}"
    JSON.parse(response)
  end

end

client = ReportingClient.new('http://api.sample.com:20960')
client.authenticate('user@sample.com','sample')

results = client.get_report('2011-02-10')

puts JSON.pretty_generate(results)

谢谢你。

PS:我知道有pycurl这个库,但我不确定我是否真的需要它。我更喜欢用Python自带的库。对我来说,pycurl可能有点过于复杂。

我刚开始学Python,看了'urllib2'的文档和一些例子,但还是找不到合适的解决方案。

2 个回答

2

你在看完urllib2的文档后,具体哪部分没明白呢?我不太懂Ruby,但看起来它主要就是发送GET请求和POST请求,数据格式是json,然后解析返回的结果。用simplejson和urllib2来处理这些事情其实非常简单。

2

这不是一个端口,但看起来你是在发送一个POST请求,然后获取授权令牌,再用这个令牌发送一个GET请求。这是我理解的内容。

import urllib
import urllib2
import simplejson
import datetime

authURL = "http://api.sample.com/authenticate"
values = {"username" : "user@sample.com",
          "password" : "sample"}

data = urllib.urlencode(values)

req = urllib2.Request(authURL, data)
response = urllib2.urlopen(req)

authToken = simplejson.load(response)["output"]

day = str(datetime.date.today())
dataURL = "http://api.sample.com/data/day/" + day + "/authToken/" + authToken

print simplejson.load(urllib2.urlopen(dataURL))

撰写回答