Python Flask and MongoDB



examples/flask-mongodb/app.py
from flask import Flask, request, render_template, abort, redirect, url_for
import pymongo
import datetime

app = Flask(__name__)

config = {
    "username": "root",
    "password": "Secret",
    "server": "mongo",
}

connector = "mongodb://{}:{}@{}".format(config["username"], config["password"], config["server"])
client = pymongo.MongoClient(connector)
db = client["demo"]

@app.route("/")
def main():
    return render_template('main.html')


@app.route("/save", methods=['POST'])
def save():
    entry = {
        "name": request.form['name'],
        "email": request.form['email'],
        "id": request.form['idnum'],
        "when": datetime.datetime.now(),
    }
    res = db.people.insert(entry)
    db.people.create_index("id", unique=True)
    return render_template('main.html')

@app.route("/list", methods=['GET'])
def list_people():
    count = db.people.count_documents({})
    people = db.people.find({})
    return render_template('list.html', count=count, people=people)

@app.route("/person/<idnum>", methods=['GET'])
def person(idnum):
    person = db.people.find_one({ 'id': idnum })
    if not person:
        abort(404)
    return render_template('person.html', person=person)


@app.errorhandler(404)
def not_found(error):
    app.logger.info(error)
    return render_template('404.html'), 404

@app.route("/get", methods=['POST'])
def get():
    name = request.form['name']
    doc = db.people.find_one({'name' : {'$regex': name}})
    if doc:
        app.logger.info(doc)
        return redirect(url_for('person', idnum=doc["id"]) )
    return render_template('main.html', error="Could not find that person")

examples/flask-mongodb/requirements.txt
flask
pytest
PyMongo

examples/flask-mongodb/templates/main.html
{% include 'incl/header.html' %}

<h2>Add a person</h2>
<form action="/save" method="POST">
  <table>
    <tr><td>Name: </td><td><input name="name"></td></tr>
    <tr><td>Email: </td><td><input name="email"></td></tr>
    <tr><td>ID: </td><td><input name="idnum"></td></tr>
  </table>
<input type="submit" value="Save">
</form>

<h2>List people by name</h2>
<form action="/get" method="POST">
Name: <input name="name">
<input type="submit" value="Get">
</form>

{% if error %}
<div style="color:red;">
  {{ error }}
</div>
{% endif %}

{% include 'incl/footer.html' %}

examples/flask-mongodb/templates/list.html
{% include 'incl/header.html' %}

<h2>List People</h2>
Total: {{ count }}

<ul>
{% for person in people %}
  <li><a href="/person/{{ person.id }}">{{ person.name }}</a></li>
{% endfor %}
</ul>

{% include 'incl/footer.html' %}

examples/flask-mongodb/templates/person.html
{% include 'incl/header.html' %}

<h2>{{ person.name }}</h2>

Email: {{ person.email }}<br>
ID: {{ person.id }}<br>
Date:: {{ person.when }}<br>

{% include 'incl/footer.html' %}

examples/flask-mongodb/templates/404.html
{% include 'incl/header.html' %}

<h2>not Found</h2>

{% include 'incl/footer.html' %}

examples/flask-mongodb/templates/incl/header.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Flask + MongoDB</h1>
<a href="/">home</a> <a href="/list">list</a>

examples/flask-mongodb/templates/incl/footer.html
<hr>
v1
</body>
</html>