Skip to content

Instantly share code, notes, and snippets.

@vjayajv
Created May 26, 2021 14:45
Show Gist options
  • Save vjayajv/72033e3075359e91ceb4413c36a58502 to your computer and use it in GitHub Desktop.
Save vjayajv/72033e3075359e91ceb4413c36a58502 to your computer and use it in GitHub Desktop.
from flask import Flask, flash, render_template, request, redirect, url_for
from pymongo import MongoClient
from bson.objectid import ObjectId
import os
# we're passing mongo's IP as env variable to docker run command
mongohost = str(os.environ['MONGOHOST'])
DEBUG = True
app = Flask(__name__,template_folder='./templates')
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'
# creating a mongo connection
mongo_uri = "mongodb://mongo:mongo@"+mongohost+":27017/prod?authSource=admin"
client = MongoClient(mongo_uri)
db = client['prod']
collection = db['prodocs']
# db and collection mentioned above automatically gets created by the script
#code for homepage does nothing other than providing links to other pages and showing doc count from mongo
# here's a link to pymongo documentation for ref : https://pymongo.readthedocs.io/en/stable/
@app.route('/')
def index():
doc_count = collection.find().count()
return render_template("index.html", response=doc_count)
# this is the code for adding docs to mongo
@app.route('/aep', methods=['GET', 'POST'])
def aep():
if request.method == "GET":
return render_template("aep.html", response="Add more key-value pairs by clicking here")
# passing response to html to be shown in the fadebox
elif request.method == "POST":
# rowcount quite useless if someone chooses to delete key-value pair inputs after adding them, but it still works
rowcount = int(request.form['rowcount'])
form_data = {}
# looping through key-value pairs and adding them to a json object
for i in range(rowcount):
try:
keyholder = "key-"+str(i)
valholder = "value-"+str(i)
key = request.form[keyholder]
val = request.form[valholder]
form_data[key] = val
except Exception:
continue
# we want to avoid adding empty json to mongo, so...
if form_data:
try:
response = collection.insert_one(form_data).inserted_id
response = "Inserted with id: "+str(response)
except Exception as err:
response = str(err)
# haven't actually used this, but might come in handy if you don't want duplicates
# don't forget to set unique index to make use of this
if (response.find('duplicate key error collection')!= -1):
response = "already exists"
else:
response = err
return render_template("aep.html", response=response)
else:
return render_template("aep.html", response="Zero inputs!")
# deleting documents from mongo
@app.route('/dep', methods=['GET', 'POST'])
def dep():
if request.method == "GET":
return render_template("dep.html")
elif request.method == "POST":
# could've simply been id or some other name, but too lazy to edit everywhere
_id = request.form['patternid']
try:
response = collection.delete_one({'_id': ObjectId(_id)})
response = str(response)
except Exception as err:
response = str(err)
print(response)
# instantly return page with updated list
return redirect("http://localhost:5000/vep", code=302)
# code for returning all the documents from mongo , could've added code for fetching one doc,
# but you can always ctrl+f and it automatically scrolls to that item from the list
@app.route('/vep', methods=['GET', 'POST'])
def vep():
if request.method == "GET":
# this is the only thing that's actually needed
documents = collection.find()
response = []
for document in documents:
document['_id'] = str(document['_id'])
response.append(document)
if not response:
response = "Nothing found in mongo! Head over to Add-docs"
return render_template("vep.html", response=response)
elif request.method == "POST":
return render_template("vep.html")
if __name__ == '__main__':
app.run(debug=True)
# haven't explained in detail because the code is pretty much straightforward and self-explainatory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment