Skip to content

Instantly share code, notes, and snippets.

@shreybatra
Last active March 19, 2018 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shreybatra/2a951d983138f94e42165a2100efa1fc to your computer and use it in GitHub Desktop.
Save shreybatra/2a951d983138f94e42165a2100efa1fc to your computer and use it in GitHub Desktop.
MongoDB connection in Flask
'''
This code is a sample code written to explain MongoDB and how to integrate it in Flask.
For full blog visit - http://www.eazydevelop.com/2018/03/mongodb-and-integration-with-flask.html
'''
from flask import Flask, request, jsonify
from pymongo import MongoClient
import pymongo
import json
from bson import json_util
#------MONGODB-CONNECTIONS---------
client = MongoClient()
db = client.carsinfo
car = db.car
#------FLASK-ENDPOINTS-------------
app=Flask(__name__)
@app.route('/',methods=['GET'])
def welcome():
return jsonify({'WELCOME':'USER'})
#------ENTER-CARS-INFORMATION-------
@app.route('/car', methods=['POST'])
def enterinfo():
name = request.json['name']
brand = request.json['brand']
cost = request.json['cost']
entry={'name':name, 'brand':brand, 'cost':int(cost)}
car.insert_one(entry)
return jsonify({'car info': 'entered'}),202
#------SHOW-CARS-INFORMATION--------
@app.route('/car', methods=['GET'])
def showcars():
name = request.args.get('name',None)
brand = request.args.get('brand',None)
cost = int(request.args.get('cost',-1))
filters = {}
if name!=None:
filters['name'] = name
if brand!=None:
filters['brand'] = brand
if cost!=-1:
filters['cost'] = cost
result = car.find(filters)
if result.count()==0:
return jsonify({'Records':'Not Found'}),404
final=[]
for i in result:
final.append(i)
return jsonify(json_util._json_convert(final)),302
#-------UPDATE-CARS---------------------
@app.route('/car', methods=['PUT'])
def updateinfo():
search = request.json['search']
searchkey = request.json['searchkey']
setkey = request.json['setkey']
setvalue = request.json['setvalue']
filters = {}
updater = {}
if search=='name':
filters['name'] = searchkey
elif search=='brand':
filters['brand'] = searchkey
elif search=='cost':
filters['cost'] = int(searchkey)
else:
return jsonify({'Bad':'Request'}),400
if setkey=='name':
updater['$set'] = {'name':setvalue}
elif setkey=='brand':
updater['$set'] = {'brand': setvalue}
elif setkey=='cost':
updater['$set'] = {'cost' : int(setvalue)}
else:
return jsonify({'Bad':'Request'}),400
result = car.update_many(filters,updater)
if(result.modified_count==0):
return jsonify({'Records':'Not Found'}),404
return jsonify({'modified':'done'}),302
#---------DELETE-CAR-INFORMATION----
@app.route('/car', methods=['DELETE'])
def deleteinfo():
delval = request.json['delval']
deletekey = request.json['deletekey']
filters = {}
if delval=='name':
filters['name'] = deletekey
elif delval=='brand':
filters['brand'] = deletekey
elif delval=='cost':
filters['cost'] = int(deletekey)
else:
return jsonify({'Bad':'Request'}),400
result = car.delete_many(filters)
#print(result.deleted_count)
if(result.deleted_count==0):
return jsonify({'Records':'Not Found'}),404
return jsonify({'deletion':'done'}),200
if __name__ == '__main__':
app.run(port=5000,use_reloader=True,debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment