This is the article to let you display the concept of database connectivity using FLask and PyMongo. PyMongo Basically a Python library. MongoDB is non-realational database. As per prequsite you may want to look at following articles before beginning with this article.

1. Setting Up and Running Python Flask Project

2. Introduction to Python Flask and Jinja2

 

I will create single pages web application using flask and PyMongo. I won't be using any templating here, rather use request to insert and view data. I have provide enough content and description so you can follow along.

 

Download Mongo DB

You can download MongoDB from official site of MongoDB. If you just want to quickly go to page follow https://www.mongodb.com/download-center?jmp=nav#community

 

Starting MongoDB Server

Following code will be valid for linux versions in particular. Please look at setup and running guide to run MongoDB in different versions

$ sudo service mongod start   # for linux versions

 

Installing all required packages

Once you have mongod in place, we need Flask and PyMongo to connect with mongo database

$ pip install flask
$ pip install pymongo

If you need more installation guide please follow following link https://api.mongodb.com/python/current/installation.html

 

Writing code

The main concept of this tutorial is to get you through quick feel of Flask and Mongo Database. I could have created views get template in place but this approach will help to grab quick knowledge to play with data.

If you like to view GitHub version of code Click Here

OR

Create any filename similar to app.py which we will use to run later

 

from flask import Flask
from pymongo import MongoClient
 
app = Flask(__name__)
client = MongoClient('localhost', 27017)
 
app.debug = True
 
db = client.app
 
# default routing provies reference to all routes
@app.route("/")
def hello():
    return 'Please follow links to make use of Mongo Database:' \
        '1. /get/ - get all users' \
        '3. /username/ - get particular user' \
        '2. /delete/username/ - delete user with username' \
        '3. /insert/username/firstname/lastname/ - insert user' \
 
# getting all registered user data
# e.g. http://localhost:5000/get/
@app.route("/get/")
def get_data():
    users = db.users.find()
    data = 'Name of Users:'
    for user in users:
        data = data + user['username'] + ': ' \
        + user['firstname'] + user['lastname'] + ', '
    return data
 
# insert user with username, firstname and password
# e.g. http://localhost:5000/insert/jeevan/Jeevan/Pant/
@app.route("/insert/")
@app.route("/insert/<username>/<firstname>/<lastname>/")
def insert_data(username=None, firstname=None, lastname=None):
    if username != None and firstname != None and lastname != None:
        db.users.insert_one({
            "username": username,
            "firstname": firstname,
            "lastname": lastname,
        })
        return 'Data inserted successfully: ' + username + ', ' \
        + firstname + ' ' + lastname
    else:
        return 'Data insufficient. Please try again!'
 
# delete user
# e.g. http://localhost:5000/delete/jeevan/Jeevan/Pant/
@app.route("/delete/")
@app.route("/delete/<username>/")
def delete_data(username=None):
    if username != None:
        db.users.remove({
            "username": username,
        })
        return 'Data delected successfully with useraname: ' + username
    else:
        return 'Provide data to delete. Please try again!'
 
# get specifi user
# e.g. http://localhost:5000/jeevan/
@app.route("/<username>/")
def users(username):
    try:
        user = db.users.find_one({'username': username})
        return user['firstname'] + ' ' + user['lastname']
    except:
        return "User couldn't be found"
 
if __name__ == "__main__":
    app.run()

 

Description/Conculusion

In above program there are various functions to carry insert, read and delete. For update your data you can use update() function.