We’ll be showing bits and pieces of the web app as it
pertains to specific sections. The entire file is less than 300
lines long, and you can inspect it by looking into the
beer.py file in the repository.
First, our imports. We need some extra imports to be able to handle exceptions properly and let us build better view queries.
from collections import namedtuple import json from Flask import Flask, request, redirect, abort, render_template from couchbase import Couchbase from couchbase.exceptions import KeyExistsError, NotFoundError from couchbase.views.iterator import RowProcessor from couchbase.views.params import UNSPEC, Query
Then, we want to set some constants for our application:
DATABASE = 'beer-sample' HOST = 'localhost' ENTRIES_PER_PAGE = 30
ENTRIES_PER_PAGE variable is used later
on to configure how many beers and breweries to show in the
Now, we’re ready to create our Flask application instance:
beer.py (creating the application).
app = Flask(__name__, static_url_path='') app.config.from_object(__name__)
The first line creates a new Flask application. The first
argument is the module in which the application is defined.
Because we’re using only a single file as our application,
we can use
__name__, which expands to the
name of the current file being executed (minus the
The second argument instructs Flask to treat unrouted URLs as
being requests for files located in the
static directory we created earlier. This
allows our templates to load the required
The second line creates a configuration object for our
app. The argument is the name of the module
to scan for configuration directives. Flask scans this module
for variable names in
UPPER_CASE and places
them in the
Then, define a function to give us a database connection:
beer.py (generating a Connection object).
def connect_db(): return Couchbase.connect( bucket=app.config['DATABASE'], host=app.config['HOST']) db = connect_db()
You already know how to connect to a Couchbase cluster, so we’ll skip the explanation here.
db variable is set to be the
Connection object. In larger applications
this is not a good idea, but we can get away with it here
because this is a simple app.