簡體   English   中英

使用Python-Flask和mongoDB傳遞用戶數據

[英]passing user data with Python-Flask and mongoDB

所以基本上我有一個“/ add”路由,它用於手動將測試用戶數據播種到mongodb,我希望能夠將該用戶的ID傳遞給路由“/ agreement”的URL,這樣當用戶打開時在協議頁面中,他們的"_id"將映射到該URI,他們在協議頁面上輸入的信息將更新我們在“/ add”路由中播種的數據。

@app.route('/add')
def add():
    users = mongo.db.users
    users.insert({
        "_id" : "autogenID",
        "_comment" : " File structure for files in client collection",
        "client_name" : "Name_of_firm",
        "contact_name" : "Name_of_contact",
        "contact_email" : "Email_ID_of_contact",
        "contact_password" : "passowrd_encryped_bcrypt",
        "client_industry" : "client_industry",
        "monthly_checks_processed": "monthly_checks_processed",
        "parent_id" : "client_id",
        "child_id" : [{
            "child_id": "client_id", 
            "child_id": "client_id"
        }],
        "agreement_authorised" : "boolean_yes_no",
        "agreement" : "agreement_text",
        "client_card" : [{
            "name_on_card": "client_name",
            "credit_card_number": "credit_card_number_bycrypt",
            "expiration_date" : "expiration_date_bycrypt",
            "credit_card_cvc" : "credit_card_cvc_bycrypt",
            "active" : "boolean_yes_no"
        }]
    })
    all_users = users.find()
    for user in all_users:
        print user


@app.route('/agreement', methods=['GET', 'POST'])
def agreenment(id):
    user = mongo.db.users.find("_id")
    print user
    return render_template('agreement.html', user=user)

我認為問題在於協議資源,也許我應該寫/agreement/<id>但我認為我缺少對<id>實例化的基本理解。 我也不完全理解協議參數的功能是什么,但我把(id)因為這似乎是為了將用戶的信息傳遞給另一個資源而必須做的事情。

我還認為user = mongo.db.users.find("_id")可能不正確以及return render_template('agreement.html', user=user) 我的一部分認為也許我應該做重定向而不是渲染,但如果有人可以伸出援助之手,我將非常感激。

嘗試這個:

@app.route('/agreement/<user_id>', methods=['GET', 'POST'])
def agreement(user_id):
    user = mongo.db.users.find_one({"_id": user_id})
    print user
    return render_template('agreement.html', user=user)

Flask中的URL參數名稱在route參數中指定,它們必須與裝飾函數的簽名匹配。

通過傳遞指定約束的dict來完成對Mongo的查詢,因此db.users.find_one({"_id": user_id})將返回單個結果,其中_id與user_id變量匹配。

編輯:實際上,根據文檔 ,您可以這樣做: db.users.find_one(user_id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM