2015-07-19 72 views
2

當我點擊提交按鈕,我得到它說的錯誤:插入數據與pymongo和瓶

"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."

這裏是我的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) 

我的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> 

回答

3

該方法已被棄用,改爲在pymongo 3.X司機.insert_one(),也有.insert_many()多個文檔創建:

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

.insert()方法現在只能在2.x和更低的系列支持。

+2

我不知道爲什麼OP得到錯誤,但都已過時['.insert()這樣'](http://api.mongodb.org/python/current/api/pymongo /collection.html#pymongo.collection.Collection.insert)仍然可以在pymongo 3.0.3中使用,當前版本爲 – styvane

+0

@ user3100115你說得對,「棄用」在這裏會更好。簡言之,這條信息就是爲了說「使用新方法」。 –

+0

米依然得到相同的錯誤..它不工作 –

1

我認爲,根本原因是在這一行:

collection = connection.signup # collection name. 

相反的評論,你得到一個DB命名signup。這應該是:

collection = db.signup 
+0

之後像這樣的代碼運行成功...但沒有數據插入db –

+0

@NeerajSharma你如何檢查? – bereal

0

請確保您對現有數據庫執行此操作,對象已成功返回。 這裏是我的代碼:

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')