0

我正在尝试通过对 Skyscanner API 的 http 请求建立连接。我知道 python 中有一个临时库可以从他们的 API 中检索数据,但出于学习目的,我想使用httplib2.

我写了以下代码:

import sys
import httplib2
from urllib.parse import urlencode


class Connection(object):
    """Connect to Skyscanner Business API and retrieve quotes"""

    API_HOST = "http://partners.api.skyscanner.net"
    PRICING_SESSION_URL = "{api_host}/apiservices/pricing/v1.0".format(
        api_host=API_HOST)
    SESSION_HEADERS = {"Content-Type": "application/x-www-form-urlencode",
                       "Accept": "application/json"}

    def __init__(self, api_key="prtl6749387986743898559646983194", body=None):
        """
        :param api_key: the API key, the default is an API key provided for
        testing purposes in the Skyscanner API documentation
        :param body: the details of the flight we are interested on
        """

        if not api_key:
            raise ValueError("The API key must be provided")

        self.api_key = api_key
        self.body = body
        self.create_session(api_key=self.api_key, body=self.body)

    def get_result(self):
        pass

    def make_request(self, service_url, method="GET", headers=None, body=None):
        """Perform either a POST or GET request

        :param service_url: URL to request
        :param method: request method, default is GET
        :param headers: request headers
        :param data: the body of the request
        """

        if "apikey" not in service_url.lower():
            body.update({
                "apikey": self.api_key
            })

        h = httplib2.Http(".cache")
        response, content = h.request(service_url,
                                      method=method,
                                      body=urlencode(body),
                                      headers=headers)
        print(str(response))

    def create_session(self, api_key, body):
        """Create the Live Pricing Service session"""

        return self.make_request(self.PRICING_SESSION_URL,
                                 method="POST",
                                 headers=self.SESSION_HEADERS,
                                 body=body)

def main():
    body = {
        "country": "UK",
        "currency": "GBP",
        "locale": "en-GB",
        "originplace": "LOND-sky",
        "destinationplace": "NYCA-sky",
        "outbounddate": "2016-05-01",
        "inbounddate": "2016-05-10",
        "adults": 1
    }

    Connection(body=body)


if __name__ == "__main__":
    sys.exit(main())

上面的代码所做的是将 POST 请求发送到他们的 API 以创建实时定价会话。要检索数据,我应该发送一个带有 URL 的 GET 请求,以轮询将在 POST 响应的 Location 标头中指定的预订详细信息。

API 密钥在他们的文档中公开可用,因为这是他们建议用于试验其 API 的通用密钥。

如果我运行上面的代码,我会得到以下响应:

{'content-length': '0', 'date': 'Sun, 24 Apr 2016 08:44:23 GMT', 'status': '415', 'cache-control': 'private'}

文档没有说明 Status 415 代表什么。

4

0 回答 0