我是python的初学者。我正在尝试从python flask应用程序连接到Mongo DB服务器。但是由于遇到以下问题,我无法运行该应用程序。
from flask import Flask, render_template
from flask_pymongo import PyMongo
from pymongo import MongoClient # Database connector
app=Flask(__name__)
app.config["MONGO_DBNAME"]="connect_to_pymon"
app.config["MONGO_URI"]="mongodb://mongo_test:mongo_test@123@ds129821.mlab.com:29821/connect_to_pymon"
mongo = PyMongo(app)
@app.route("/add")
def add():
user = mongo.db.users
user.insert[{"name":"kishor"}]
return "users added!"
if __name__=='__main__':
app.run(debug=True, port=8080)
这是我的源代码。当我执行此操作时,出现以下错误,无法跟踪它。
Traceback (most recent call last):
File "C:/Users/kravi/PycharmProjects/GitUploadTest/mongoTest.py", line 9, in <module>
mongo = PyMongo(app)
File "C:\Kishor\Training\My_Workspace\Python_Basics\TaskCRUD\venv\lib\site-packages\flask_pymongo\__init__.py", line 116, in __init__
self.init_app(app, uri, *args, **kwargs)
File "C:\Kishor\Training\My_Workspace\Python_Basics\TaskCRUD\venv\lib\site-packages\flask_pymongo\__init__.py", line 149, in init_app
parsed_uri = uri_parser.parse_uri(uri)
File "C:\Kishor\Training\My_Workspace\Python_Basics\TaskCRUD\venv\lib\site-packages\pymongo\uri_parser.py", line 379, in parse_uri
user, passwd = parse_userinfo(userinfo)
File "C:\Kishor\Training\My_Workspace\Python_Basics\TaskCRUD\venv\lib\site-packages\pymongo\uri_parser.py", line 97, in parse_userinfo
"RFC 3986, use %s()." % quote_fn)
pymongo.errors.InvalidURI: Username and password must be escaped according to RFC 3986, use urllib.parse.quote_plus().
Process finished with exit code 1
注意:我尚未在PC中安装mongoDb。我正在使用mongo db作为服务
答案 0 :(得分:1)
您可以使用PyMongo如下连接数据库:
from pymongo import MongoClient
client = MongoClient("mongodb://mongo_test:mongo_test@123@ds129821.mlab.com:29821/connect_to_pymon")
db = client["dbname"] # connect_to_pymon in your case
答案 1 :(得分:0)
我了解到,在密码中使用特殊字符(如“ @”)没有意义,因为我们必须配置mongo URI,它具有带有@符号的特定格式。我更改了数据库密码,然后尝试了。!