简体   繁体   English

用pymongo和flask插入数据

[英]Insert data into with pymongo and flask

when i click on submit button i get an error which says: 当我单击提交按钮时,出现错误提示:

"TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Database' object it is failing because no such method exists." “ TypeError:'Collection'对象不可调用。如果您打算在'Database'对象上调用'insert'方法,则该方法将失败,因为不存在这样的方法。”

here is my signin.py code : 这是我的signin.py代码:

from flask import Flask, request, render_template
from pymongo import MongoClient

@app = Flask(__name__)
connection = MongoClient()
db = connection.project #database name.
collection = connection.signup # collection name.

@app.route('/signin/')
def index_show():
     return render_template('signin.html')

@app.route('/signin/', methods = ['POST'])
def signup_form():
   username = request.form['user']
   passowrd = request.form['pass']
   collection.insert({'user': username, 'passoword': passowrd})

if __name__ == '__main__':
   app.run(debug = True)

my html file code is here : 我的html文件代码在这里:

  <!DOCTYPE html>
 <html>
  <head>
    <title></title>
  </head>
  <body>
     <form method="post" action=".">
       <input type="text" name="user" /><br/><br/>
       <input type="password" name="pass" /><br/><br/>
       <input type="submit" name="submit" /><br/><br/>
     </form>
 </body>

The method has been deprecated and is changed to .insert_one() in the pymongo 3.x driver, there is also .insert_many() for multiple document creation: 该方法已被弃用,并在pymongo 3.x驱动程序中更改为.insert_one() ,还有.insert_many()用于创建多个文档:

collection.insert_one({'user': username, 'passoword': passowrd})

The .insert() method is now only supported in the 2.x and lower series. 现在,仅2.x及更低版本中支持.insert()方法。

I think, the root cause is in this line: 我认为,根本原因在于:

collection = connection.signup  # collection name.

Contrary to the comment, you're getting a DB named signup . 与注释相反,您得到一个名为signup的数据库。 That should rather be: 那应该是:

collection = db.signup

please do make sure that you do this to an existing database,object has been returned successfully. 请确保对现有数据库执行此操作,对象已成功返回。 here is my code: 这是我的代码:

from pymongo import MongoClient

client=MongoClient()
db=client.testdb
new={"shopclues":1234,"rating":3}
result=db.testdb.insert_one(new)   
result.inserted_id
ObjectId('59e2f0f2031b4b0b27ecfa09')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM