Добавление нового элемента в курсор Pymongo - PullRequest
0 голосов
/ 02 января 2019

Я пытаюсь добавить новое поле в строку 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-адресом в нем, но я не могу заставить это работать.

1 Ответ

0 голосов
/ 02 января 2019
  • Я думаю, что причина, по которой ваши изменения не отражаются, в том, что вы пытаетесь получить доступ к документам внутри курсора с помощью индекса (например, списка), но это, похоже, не работает.
  • В вашем последнем утверждении вы пытаетесь вернуть объект курсора непосредственно в функцию render_template, что неверно.Объект курсора не является списком (список python) документов json, как вы предполагаете.

Приведенный ниже код будет работать, если вы хотите просто увидеть изменения, которые отражаются.

        @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)
...