我正在尝试向json字符串(或更确切地说是bson字符串)添加新字段,以便可以将其传递到前端。
我做了很多研究,我尝试将结果像字典一样对待,我尝试将字段添加到数据库中,但还是一无所获。
@app.route('/')
@app.route('/index')
def index():
i=10
make = db.cars.distinct("Make")
model = db.cars.distinct("Short Model")
year = db.cars.distinct("Year introduced")
results = db.cars.find().limit(i)
print(results[0]['Make'])
x=0
while x < i:
print(x)
r = requests.get('https://izrite.com:5555/image/' + results[x]['Vehicle ID'])
r=r.json()
print(results[x])
results[x]['carImage'] = r['url']
print(results[x])
x=x+1
print("finished")
return render_template('index.html', title='Home', numresults=str(i), make=make, model=model, year=year, results=results)
现有字符串
{'_id': ObjectId('5c2bebbe7b94a040bce5eadf'), 'Vehicle ID': '74908', 'Make': 'MERCEDES-BENZ', 'Short Model': 'A CLASS', 'Long Model': 'A CLASS HATCHBACK', 'Trim': 'SE', 'Derivative': 'A160 SE 5dr Auto', 'Year introduced': '2016', 'Year discontinued': '', 'Currently Available': 'Y'}
所需字符串
{'_id': ObjectId('5c2bebbe7b94a040bce5eadf'), 'Vehicle ID': '74908', 'Make': 'MERCEDES-BENZ', 'Short Model': 'A CLASS', 'Long Model': 'A CLASS HATCHBACK', 'Trim': 'SE', 'Derivative': 'A160 SE 5dr Auto', 'Year introduced': '2016', 'Year discontinued': '', 'Currently Available': 'Y', 'carImage': 'http://images.capnetwork.co.uk/VehicleImage.aspx?SUBID=152231&HASHCODE=FE9015D10FEB72AE9042DB62DAC0ACFE&DB=car&CAPID=74908&VIEWPOINT=3'}
我希望在json字符串中有一个名为carImage的新字段,其中包含url,但我无法使它正常工作。
答案 0 :(得分:0)
render_template
函数中返回游标对象,这是错误的。游标对象不是您假设的json文档列表(python列表)。如果您只想看到更改,下面的代码将起作用。
@app.route('/')
@app.route('/index')
def index():
i=10
make = db.cars.distinct("Make")
model = db.cars.distinct("Short Model")
year = db.cars.distinct("Year introduced")
results = db.cars.find().limit(i)
#print(results[0]['Make'])
for doc in results:
r = requests.get('https://izrite.com:5555/image/' + results[x]['Vehicle ID'])
r=r.json()
print(doc)
doc['carImage'] = r['url']
print(doc)
print("finished")
# return render_template('index.html', title='Home', numresults=str(i), make=make, model=model, year=year, results=results)
如果要更新所有文档并返回,则将find()
的结果转换为如下列表。但是,请注意,它将所有文档加载到内存中。
@app.route('/')
@app.route('/index')
def index():
i=10
make = db.cars.distinct("Make")
model = db.cars.distinct("Short Model")
year = db.cars.distinct("Year introduced")
results = list(db.cars.find().limit(i)) #Note that here we convert the result to a list
#print(results[0]['Make'])
for doc in results:
r = requests.get('https://izrite.com:5555/image/' + results[x]['Vehicle ID'])
r=r.json()
print(doc)
doc['carImage'] = r['url']
print(doc)
print("finished")
return render_template('index.html', title='Home', numresults=str(i), make=make, model=model, year=year, results=results)