【发布时间】:2017-05-14 03:02:57
【问题描述】:
我在 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 调用中没有返回上面的 listOfVehicles,而是我得到了神秘的
TypeError: 'list' object is not callable
现在,如果我注释掉最后一行,并取消注释 jsonify 行,就可以了。 但是在前端解析返回的对象很痛苦。我只想返回 listOfVehicles,但我不知道为什么它不让我。
编辑: 我忘记了上面定义的 Train 类:
class Train:
def __init__(self):
self.bearing = None
self.blockID = None
self.delay = None
self.direction = None
self.extraBlockID = None
self.garage = None
self.inCongestion = False
self.latitude = None
self.longitude = None
self.lastLocID = None
self.nextLocID = None
self.offRoute = False
self.signMessageLong = None
self.time = None
self.tripID = None
self.vehicleID = None
def __html__(self):
return {
"Bearing": self.bearing,
"BlockID": self.blockID,
"Delay": self.delay,
"Direction": self.direction,
"extraBlockID": self.extraBlockID,
"Garage": self.garage,
"inCongestion": self.inCongestion,
"Latitude": self.latitude,
"Longitude": self.longitude,
"lastLocID": self.lastLocID,
"nextLocID": self.nextLocID,
"offRoute": self.offRoute,
"signMessageLong": self.signMessageLong,
"time": self.time,
"vehicleID": self.vehicleID,
"TripID": self.tripID
}
编辑2: 调用 fetch_trains():
@app.route('/')
@app.route('/get_trains', methods=['GET', 'OPTIONS'])
def get_trains():
train_list = fetch_trains()
return train_list
【问题讨论】:
-
听起来
fetch_trains的调用者有问题... -
我认为问题超出了您在此处发布的范围。
-
怎么样?我应该走哪条路?
标签: python json python-3.x flask