connection with mongo server from python

I'm a beginner at python. I'm trying to connect to Mongo DB server from my python flask application. But I couldn't able to run the application as I'm facing the below problem.

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)

This is my source code. When I execute this I'm getting the following error which I couldn't able to trace it.

Traceback (most recent call last):
  File "C:/Users/admin/PycharmProjects/FirstMongoApp/PyMongoApp.py", line 9, in <module>
    mongo = PyMongo(app)
  File "C:\Users\admin\PycharmProjects\FirstMongoApp\venv\lib\site-packages\flask_pymongo\__init__.py", line 116, in __init__
    self.init_app(app, uri, *args, **kwargs)

Note: I haven't installed mongoDb in my PC. I'm using mongo db as a service

1 answer

  • answered 2018-07-07 13:13 Prajval M

    you can connect to your db using PyMongo as follows:

    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