Python Flask and MongoDB



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

app = Flask(__name__)

config = {
    "username": "root",
    "password": "Secret",
    "server": "my-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():
    field = request.form['field']
    value = request.form['value']
    entry = {
        "field": field,
        "value": value,
        "when": datetime.datetime.now(),
    }
    res = db.people.insert(entry)
    doc = db.people.find_one({'field' : field})
    app.logger.debug(doc)
    doc = db.people.find_one({'field' : field})
    new_value = doc["value"]
    return render_template('main.html', saved=1, value=new_value)

@app.route("/get", methods=['POST'])
def get():
    field = request.form['field']
    doc = db.people.find_one({'field' : field})
    if doc is None:
        return render_template('main.html', field=field, value="Not defined yet")
    str_value = doc["value"]
    return render_template('main.html', field=field, value=str_value)

examples/flask-mongodb/templates/main.html
<form action="/save" method="POST">
<input name="field">
<input name="value">
<input type="submit" value="Save">
</form>

<form action="/get" method="POST">
<input name="field">
<input type="submit" value="Get">
</form>

{% if saved %}
<b>saved</b>
{{ value }}
{% endif %}

{% if field %}
  The value of <b>{{ field }}</b> is <b>{{ value }}</b>
{% endif %}

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

examples/flask-mongodb/Dockerfile
FROM ubuntu:20.04
RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y python3

RUN apt-get install -y python3-pip

COPY requirements.txt /opt/
RUN pip3 install -r /opt/requirements.txt

WORKDIR /opt
CMD FLASK_APP=app FLASK_DEBUG=1 flask run --host 0.0.0.0 --port 5000

examples/flask-mongodb/docker-compose.yml
version: '3.7'
services:
  web:
    build: .
    ports:
    - "5001:5000"
    volumes:
    - .:/opt
    links:
    - mongo
  mongo:
    image: mongo
    container_name: my-mongo
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: Secret

docker-compose up