Posted on

Pyramid 02: MongoDB Setup

Our goal here is to get our MongoDB database running and read from it.

First install MongoDB on your system. If you use Ubuntu the links below may be useful:
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/
https://www.hostinger.com.br/tutoriais/instalar-mongodb-ubuntu
https://www.howtoforge.com/tutorial/install-mongodb-on-ubuntu/

In order to visualize the data there are some tools like Compass and Robo 3T (https://robomongo.org/). I will be using Robo 3T.

Open Robo 3T and create a new database task_manager_db.
Inside the task_manager_db create a collection ‘tasks’.
Inside the collection ‘tasks’ insert the document below:

{
    name: "Task 01",
    active: 1
}

{
    name: "Task 02",
    active: 1
}

{
    name: "Task 03",
    active: 1
}

We now have 3 items at our task collection. These items will be shown at our home page.

Let’s access our database using our application.
Open the file development.ini and insert mongo_uri as indicated:

[app:main]
use = egg:task_manager

pyramid.reload_templates = true
pyramid.debug_authorization = false
pyramid.debug_notfound = false
pyramid.debug_routematch = false
pyramid.default_locale_name = en
pyramid.includes =
    pyramid_debugtoolbar

mongo_uri = mongodb://localhost/task_manager_db

Important: for the sake of simplicity we did not use any sort of authentication at our database at this project.

At our task_manager/__init__.py lets connect to the database.

First import pymongo then let’s adjust our Configurator.
The code will be as below:

from pyramid.config import Configurator
from urllib.parse import urlparse
from pymongo import MongoClient


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    with Configurator(settings=settings) as config:
        db_url = urlparse(settings['mongo_uri'])
        config.registry.db = MongoClient(
            host=db_url.hostname,
            port=db_url.port,
        )

        def add_db(request):
            db = config.registry.db[db_url.path[1:]]
            if db_url.username and db_url.password:
                db.authenticate(db_url.username, db_url.password)
            return db

        config.add_request_method(add_db, 'db', reify=True)

        config.include('pyramid_jinja2')
        config.include('.routes')
        config.scan()
    return config.make_wsgi_app()

At the setup.py requires section it should be ( include pymongo):

requires = [
    'pyramid',
    'pyramid_jinja2',
    'pyramid_debugtoolbar',
    'waitress',
    'pymongo',
]

At the folder that contains setup.py run the following command to install pymongo:

env/bin/pip install -e .

The project should be able to run now, but we haven’t accessed our database.
Let’s change our view my_view to list all the content of our database.
At the file views.py rename my_view to task_list, then we will have the following:

from pyramid.view import view_config


@view_config(route_name='home', renderer='templates/home.jinja2')
def task_list(request):
    tasks = request.db['tasks'].find()
    return {
        'tasks': tasks,
        'project': 'task_manager',
    }

At this point we passed to our view a dictionary with the key ‘tasks’ that contains all the tasks on our database.
Let’s edit our template home.jinja2 in order to show this data.

{% extends "layout.jinja2" %}

{% block content %}
<div class="content">
  <h1><span class="font-semi-bold">Pyramid</span> <span class="smaller">Starter project</span></h1>
  <p class="lead">Welcome to <span class="font-normal">{{project}}</span>, a&nbsp;Pyramid application
    generated&nbsp;by<br><span class="font-normal">Cookiecutter</span>.</p>
</div>
<hr>
<h1> Tasks</h1> <br>
<ul>
  {% if tasks %}

  {% else %}
  <li>No tasks</li>
  {% endif %}
  {% for task in tasks %}
  <li>
    {{task.name}}
  </li>

  {% endfor %}
</ul>

{% endblock content %}

Now run the project and you will see that we can read our database and all the items we have inserted are listed at the main page.

env/bin/pserve development.ini --reload

You can find the code for this part of the project at the part02 branch of the project repository.
To clone and run the specific branch use:

git clone -b part02 https://github.com/albertosdneto/tutorial_pyramid_mongo.git
cd tutorial_pyramid_mongo/
python3 -m venv env
env/bin/pip install --upgrade pip setuptools
env/bin/pip install -e .
env/bin/pserve development.ini --reload