如何用Python从MongoDB中取出特定键的值

2024-06-06 16:14:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我确信这很简单,但是我需要从键值对中提取一个值来检查它是否与会话中的用户名匹配。(我用的是pymongo)

其中一个MongoDB对象的示例如下('jam\u or \u event'是集合名称):

_id: ObjectId("5d44545037b30613b88ae587")
jam_title: "Test Jam 2"
genre: "Rock"
date_of_jam: "2 August, 2019"
jam_location: "Test Address 2"
jam_county: "Bristol"
jam_member_1: "TestUser2"
member_instrument_1: "Drums"
jam_notes: "Test 2"
jam_owner: "TestUser2"

值会随着对象而改变,但我希望能够从当前选定的对象中提取jam\u owner值,并询问它是否与当前登录的用户的用户名相同。如果他们匹配,他们将有更多的特权在页面上。你知道吗

下面是python函数的代码:

@app.route('/edit_jam/<jam_id>', methods=['POST', 'GET'])
def edit_jam(jam_id):
    user_logged_in = 'username' in session
    the_jam =  mongo.db.jam_or_event.find_one({"_id": ObjectId(jam_id)})
    username=session['username']

    if request.method == 'POST':
        if user_logged_in:
            jams = mongo.db.jam_or_event
            jams.update( {'_id': ObjectId(jam_id)},
            {
                'jam_title':request.form.get('jam_title'),
                'genre':request.form.get('genre'),
                'date_of_jam': request.form.get('date_of_jam'),
                'jam_location': request.form.get('jam_location'),
                'jam_county':request.form.get('jam_county'),
                'jam_member_1':request.form.get('jam_member_1'),
                'member_instrument_1':request.form.get('member_instrument_1'),
                'jam_notes':request.form.get('jam_notes'),
            })
            return redirect(url_for('get_jams'))
    return render_template('editjam.html',
        jam=the_jam,
        instruments=mongo.db.instruments.find(),
        counties=mongo.db.counties.find(),
        username=session['username'])

然后我想说,在html中

{% if jam_owner == username %}
xyz
{% endif %}

Tags: or对象testformeventiddbget
1条回答
网友
1楼 · 发布于 2024-06-06 16:14:34

好吧,我不知道你是不是这个意思,但我希望我能正确理解,虽然问起来很简单。你知道吗

好的,这段代码从Mongo db返回对象:

the_jam =  mongo.db.jam_or_event.find_one({"_id": ObjectId(jam_id)}) # so the_jam will hold the Object (Dictionary) from Mongodb.

您可以访问您的jam\u所有者或任何其名称:

the_jam[key] # as key you want to get jam owner value I think so it will be the_jam["jam owner"]

因为username变量中有用户名,所以可以比较:

if username == the_jam["jam owner"]:
# ....

相关问题 更多 >