【问题标题】:passing user data with Python-Flask and mongoDB使用 Python-Flask 和 mongoDB 传递用户数据
【发布时间】:2016-06-11 17:20:27
【问题描述】:

所以基本上我有一个“/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) 可能不正确。我的一部分认为也许我应该做重定向而不是渲染,但如果有人能伸出援助之手,我将不胜感激。

【问题讨论】:

  • 您应该避免使用id 作为标识符,因为您最终会遮蔽built-in function

标签: python mongodb rest flask


【解决方案1】:

试试这个:

@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 参数中指定,它们必须与修饰函数的签名相匹配。

在 Mongo 中的查询是通过传递一个指定约束的 dict 来完成的,因此db.users.find_one({"_id": user_id}) 将返回一个 _id 与 user_id 变量匹配的结果。

编辑:实际上,根据the documentation,您可以这样做: db.users.find_one(user_id).

【讨论】:

    猜你喜欢
    • 2012-11-03
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多