我在一个Flask应用程序中有一个函数,它返回一些API数据
def fetch_trains():
r = requests.get('https://developer.trimet.org/ws/v2/vehicles/appID/[app id goes here]')
vehicles = r.json()
listOfVehicles = []
for vehicle in vehicles['resultSet']['vehicle']:
if vehicle['type'] =='rail':
vehToAdd = Train()
vehToAdd.bearing = vehicle['bearing']
vehToAdd.blockID = vehicle['blockID']
vehToAdd.delay = vehicle['delay']
vehToAdd.direction = vehicle['direction']
vehToAdd.extraBlockID = vehicle['extraBlockID']
vehToAdd.gararge = vehicle['garage']
vehToAdd.inCongestion = vehicle['inCongestion']
vehToAdd.latitude = vehicle['latitude']
vehToAdd.longitude = vehicle['longitude']
vehToAdd.lastLocID = vehicle['lastLocID']
vehToAdd.offRoute = vehicle['offRoute']
vehToAdd.signMessageLong = vehicle['signMessageLong']
vehToAdd.time = vehicle['time']
vehToAdd.tripID = vehicle['tripID']
vehToAdd.vehicleID = vehicle['vehicleID']
vehToAdd.nextLocID = vehicle['nextLocID']
listOfVehicles.append(vehToAdd)
#return jsonify({'List of vehicles':listOfVehicles})
return listOfVehicles
上面的车辆列表并没有在API调用中返回,我得到的是一个谜
^{pr2}$现在,如果我注释掉最后一行,并取消对jsonify行的注释,就可以了。但是在前端解析返回的对象是一件痛苦的事。我想把车的清单还给我,但我不知道为什么不让我。在
编辑时间: 我忘了上面定义的火车等级:
^{3}$编辑2: 调用fetch_trains():
@app.route('/')
@app.route('/get_trains', methods=['GET', 'OPTIONS'])
def get_trains():
train_list = fetch_trains()
return train_list
问题是你的代码试图返回一个
list
。Flask不希望从view函数返回list
对象,而是response
对象,引用official doc。jsonify
正在工作,因为它返回一个JSON响应对象。在如果只想返回listOfVehicles,可以将其指定给一个变量,然后将其呈现到模板中,如下所示:
在模板
^{pr2}$index.html
中:它将在
train_list
上循环,显示index.html
中的所有内容。在相关问题 更多 >
编程相关推荐