How to connect MongoDB with Flask using Pymongo And Crud Operation with mongoDB

Sagarvermaitdeveloper
3 min readMay 30, 2020

Hello Techie People, Today i am going to write to interesting blog on crud operation with python using flask. so let’s start.

Step 1 : Just install pymongo using pip, to install this please use this command

python -m pip install pymongo

Step 2 : Make a fresh page and Name them in register.py

And run these commands for install flask and requests

python -m pip install requests

python -m pip install flask

python -m pip install flask_pymongo

Step 3 : We need to import these modules in our register.py

from flask import Flask
from flask_pymongo import PyMongo
from flask import jsonify
import request

To connect with mongoDB atlas we need srv url so we need to install pymongo[‘srv’] so install this by using this command.

python3 -m pip install 'pymongo[srv]'

Step 4 : And now initialize the application with this code.

app = Flask(__name__)

Step 5 : Now Connect with our mongoDB application.

app.config['MONGODB_NAME'] = 'test'
app.config['MONGO_URI'] = 'mongodb+srv://name:<Your Password>@your connectiontr.mongodb.net/test?retryWrites=true&w=majority'

connection established with this code

mongo = PyMongo(app)

So make a first route for the GET method in flask using python

@app.route('/users', methods=['GET'])
def get_all_users():
users = mongo.db.users
output = []
for s in users.find():
output.append({'name' : s['name'], 'email' : s['email'],'password' : s['password']})
return jsonify({'result' : output})

And paste this code in bottom of your code for make a server on http

if __name__ == "__main__" :
app.run(host='127.0.0.1',port=4000)
app.run(debug=True)

Check on http://localhost:4000/users , this will return a beautiful json.

And Now make a post request in flask using Python.

Before that we need to install some more modules

from bson.json_util import dumps
from bson.objectid import ObjectId
from flask import jsonify,request
from werkzeug.security import generate_password_hash,check_password_hash
from app import mongo,app
import json

And paste this codes into the post route

@app.route('/users', methods=['POST'])def postUser() : 
logger.debug("inside post method")
json = request.get_json()
name = json['name']
email = json['email']
password = json['password']
#basic validation
if name and email and password and request.method == 'POST':
#GENERATE HASH PASSWORD
hashed_password = generate_password_hash(password)
#Insert the data
users = mongo.db.users
user_id = users.insert({'name': name, 'password': hashed_password,'email' : email})
new_user = users.find_one({'_id': user_id})
output = {'name': new_user['name'], 'password': new_user['password'], 'email': new_user['email']}
return jsonify({'result': output},201)

This will create the user

Now we need to update the user using put method

@app.route('/users', methods=['POST'])def updateUser() :
logger.debug("inside put method")
_id = taskId
json = request.get_json()
name = json['name']
email = json['email']
password = json['password']
# basic validation
if name and email and password and request.method == 'PUT':
# GENERATE HASH PASSWORD
hashed_password = generate_password_hash(password)
# Update the data
users = mongo.db.users
user_id = users.update_one({'_id' : ObjectId(_id['$oid']) if '$oid' in _id else ObjectId(_id)},{'$set' : {'name': name, 'password': hashed_password, 'email': email}})
update_user = users.find_one({'_id': user_id})
output = {'name': update_user['name'], 'password': update_user['password'], 'email': update_user['email']}
return jsonify({'result': output}, 201)

This will update the User.

Now delete the User.

@app.route('/users', methods=['DELETE'])def updateUser() :
mongo.db.users.delete_one({"_id" : ObjectId(taskId)})
response = {"message" : "user deleted successfully"}
return jsonify(response)
logger.debug("inside delete method")
return {"message": "from delete method"}, 200

This will delete the user.

So we complete the crud application and my full code repository link is given below.

Tech Sagar!

--

--