史基浦航班api,用python获取航班信息出错



我正试图从schiphol(阿姆斯特丹机场(的公共api中获取数据。我从获取此apihttps://api.schiphol.nl/public-flights/flights.

我正在使用python获取飞行数据。在我的代码中,我得到一个错误,即"app_id"在填充时为none…

控制台中的完整错误:用法:flight_info_api.py[选项]

flight_info_api.py:错误:请提供应用程序id(-i,--app_id(

有人能看到出了什么问题吗?

我的代码:

import requests
import sys
import optparse

def callPublicFlightAPI(options):
url = 'https://api.schiphol.nl/public-flights/flights'
headers = {
'resourceversion': 'v4',
'app_id': 'b209eb7f',
'app_key': '0b6c58b5ae4595dd39785b55f438fc70'
}
try:
response = requests.request('GET', url, headers=headers)
except requests.exceptions.ConnectionError as error:
print(error)
sys.exit()
if response.status_code == 200:
flightList = response.json()
print('found {} flights.'.format(len(flightList['flights'])))
for flight in flightList['flights']:
print('Found flight with name: {} scheduled on: {} at {}'.format(flight['flightName'],
       flight['scheduleDate'],
       flight['scheduleTime']))
else:
print('''Oops something went wrong Http response code: {}{}'''.format(response.status_code, response.text))

if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-i', '--app_id', dest='app_id',
help='App id used to call the API')
parser.add_option('-k', '--app_key', dest='app_key',
help='App key used to call the API')
(options, args) = parser.parse_args()
if options.app_id is None:
parser.error('Please provide an app id (-i, --app_id)')
if options.app_key is None:
parser.error('Please provide an app key (-key, --app_key)')
callPublicFlightAPI(options)

您需要将其添加到页眉中:"Accept":"application/json">

祝你好运。

编辑:

基本上,由于您希望以json形式接收数据,因此必须将"Accept":"application/json"添加到标头中。在这种情况下,您的标题将如下所示:

headers = {
'Accept': 'application/json',
'resourceversion': 'v4',
'app_id': YOUR_APP_ID,
'app_key': YOUR_APP_KEY
}

当您要发出请求时,必须在参数中添加标头。您的请求将如下所示:

response = requests.get(URL, headers=headers)

我希望这能有所帮助!

最新更新