It’s time for a practical project: let’s build a blog using MongoDB as the database. This tutorial combines the database knowledge you’ve gained with Bottle, a fast and lightweight Python web framework. This project will demonstrate the full lifecycle of a web application, from handling user input in a web form to storing and retrieving data from a NoSQL database.
Table of Contents
💻 Introducing the Bottle Framework
Bottle is a micro web-framework for Python. It’s incredibly simple, consisting of a single file module with no dependencies outside the Python Standard Library. It’s perfect for quickly building web applications and APIs. The core of Bottle is routing, which maps a URL to a Python function that handles the request.
from bottle import route, run, template
@route('/hello/<user>')
def index(user):
return template('<h2>Hello {{user}}!</h2>', user=user)
run(host='localhost', port=1234)
Here, the @route(...)
decorator tells Bottle that any request to a URL like `/hello/Mihalis` should be handled by the `index` function.
💻 Connecting Bottle to MongoDB
The connection between Bottle and MongoDB is made using the PyMongo driver. Within your URL handler functions, you can establish a connection to your MongoDB server, query a collection, and then pass the results to a template for rendering.
from pymongo import MongoClient
@route('/list')
def listAllPosts():
client = MongoClient('localhost', 27017)
db = client.LXF
cursor = db.blogposts.find()
# The 'cursor' object now contains all posts
return template('listPosts', data=cursor)
💻 Creating and Displaying Posts
Our blog needs a way to create new posts and display them.
- The View (Template): We’ll create a template file (e.g.,
write.tpl
) with an HTML form that has fields for a title and body. This form will `POST` its data to a specific URL. - The Controller (Route): A Python function decorated with
@post('/presentnewpost')
will handle the form submission. It will extract the title and body from the request, create a document, and insert it into the `blogposts` collection in MongoDB. - Displaying Posts: Another route, like
@get("/post/<postid>")
, will retrieve a specific post from the database using its unique `_id` and pass it to a template (`showsinglepost.tpl`) for display.
More Topics
- Redis Guide: The High-Speed In-Memory Data Store
- Riak NoSQL Guide: What’s the Big Deal?
- MongoDB Guide: An Admin’s Guide to Maximum Power
- MongoDB Guide: Using Native Drivers with Python and Ruby
- MariaDB Guide: The Open Source MySQL Alternative
- SQLite3 Guide: Getting Started with Python
- A Beginner’s Guide to Go: Explore Functions