gpt4 book ai didi

python - 来自 Python 的 QPX Express API

转载 作者:太空宇宙 更新时间:2023-11-04 08:59:52 25 4
gpt4 key购买 nike

我正在尝试通过 python 使用 Google 的 QPX Express API。我在发送请求时一直遇到一些问题。起初我尝试的是这样的:

url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=MY_KEY_HERE"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)

基于以下代码:urllib2 and json

当我运行上面的代码时,我收到以下错误消息:

TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.

我搜索了一个解决方案并根据以下问题调整了我的代码:TypeError: POST data should be bytes or an iterable of bytes. It cannot be str

我将我的代码更改为:

url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyCMp2ZnKI3J91sog7a7m7-Hzcn402FyUZo"
values = {"request": {"passengers": {"kind": "qpxexpress#passengerCounts", "adultCount": 1}, "slice": [{"kind": "qpxexpress#sliceInput", "origin": "RDU", "destination": location, "date": dateGo}]}}
data = json.dumps(values)
data = data.encode("utf-8")
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
print(response)

但是,当我运行这段代码时,我收到以下错误消息:

urllib.error.HTTPError: HTTP Error 400: Bad Request

我也尝试过将 utf-8 更改为 ascii,但我没有成功。我怎样才能让它正常工作?

最佳答案

这是一个使用 excelent requests 库的解决方案。

import json
import requests

api_key = "YOUR API KEY HERE"
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=" + api_key
headers = {'content-type': 'application/json'}

params = {
"request": {
"slice": [
{
"origin": "TXL",
"destination": "LIM",
"date": "2015-01-19"
}
],
"passengers": {
"adultCount": 1
},
"solutions": 2,
"refundable": False
}
}

response = requests.post(url, data=json.dumps(params), headers=headers)
data = response.json()
print data

我不确定您的请求为何不起作用。也许真的是请求参数错了。日期绝对需要在未来!

关于python - 来自 Python 的 QPX Express API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26550213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com