/How To Deploy Python Web Applications with the Bottle Micro Framework on Ubuntu 16.04

How To Deploy Python Web Applications with the Bottle Micro Framework on Ubuntu 16.04

Python is a programming language that is freely available and that makes solving a computer problem almost as easy as writing out one’s thoughts about the solution. It can be written once and run on almost any computer without needing to change the program. Python is a general-purpose programming language that is able to be used on any modern computer operating system. It may easily be used for processing text, numbers, images, scientific data, or anything else which one might save on a computer. Increasingly, large applications are written almost exclusively in Python. It is used daily in the operations of the Google search engine, the video sharing website YouTube, NASA , and the New York Stock Exchange. These are but a few of the places where Python plays important roles in the success of a business, government, and non-profit organizations; there are many others.

Bottle is a Python framework that falls into the second category. It is similar to Flask, however, it focuses very strongly on staying out of your way as much as possible. It is extremely lightweight but makes it very easy to develop applications quickly.
In this article, we will cover the installation set-up and use of Bottle to create simple web applications on an Ubuntu 16.04 server.

Prerequisites:

Prepare you Ubuntu 16.04 server with its FQDN and assign an IP address. Then login to your server using sudo or root user credentials and update with latest patches using below command.

$ sudo apt-get update

Setup Virtual Environment for Python:

Ubuntu 16.04 comes with both Python 2 and Python 3 installed. Typing python at the shell prompt still launches Python 2. Use the command ‘python3’ for Python 3.

The virtualenv software allows us to create a separate, contained environment for our Python projects that will not affect the entire OS. To do so, we will install the python-virtualenv package to isolate our Python project from the system’s Python environment. Run the below command to install the package and press Y key to continue when you asked.

$ sudo apt-get install python-virtualenv

python-vitualenv

After installation create a new folder projects in our home directory, and then create a virtual environment within newly created folder using below commands.

$ mkdir ~/projects
$ cd ~/projects
$ virtualenv --no-site-packages venv

This will creates a directory called venv within the current directory and installs some Python utilities and creates a directory structure to install additional tools.

venv-directories

Enabling Virtual Environment for Python:

Now are going enable virtual environment for Python before beginning to work on our project. Run the below command to do so.

ubuntu@ubuntu-16:~/projects$ source venv/bin/activate
(venv) ubuntu@ubuntu-16:~/projects$

The command prompt will change to (venv) , reflecting that we are operating in a virtual environment now. So, whenever you need to reconnect to the Python’s virtual environment , you will be required to run this command within the projects directory.

Installing Bottle:

We will use pip utility that was installed as a part of virtualenv package. This tool allows us to easily install Python packages from the Python package index, an online repository. Let’s run the command below to search for Python packages that can be used with Bottle.

$ pip search bottle

You will see a list of multiple packages available for bottle. Now run below command to install bottle using pip utility.

$ pip install bottle

install-bottle

After completing the installation, now we can use the Bottle framework within our applications.

Creating a Bottle Application:

Bottle applications can be incredibly simple. In their most bare form, they can implement all of these components within a single file. We will create a “hello world” application to show how this works.

Bottle implements a version of the MVC software pattern like most other frameworks do. MVC stands for model, view, and controller, and it describes a decision to separate the different functions of a user interface.

Let’s create a Python application called hello.py using your command line editor like we are using ‘vim’ here.

$ vim ~/projects/hello.py
from bottle import route, run
@route('/hello')
def hello():
    return "Hello World!"
run(host='0.0.0.0', port=8080)

Here the first line tells our program that we want to import the route and run modules from the Bottle package. Then we added a route that matches the URL pattern ‘/hello’.

This route decorator matches the URL /hello, so when that path is requested on the server, the function that directly follows will be executed.

It returns a value that can be displayed in the web browser. In this case, the value is a simple HTML string. We could remove the h1 header tags and the same information would be displayed in an undecorated fashion.

In the end , we need to run our application using the development server by add the final line and save file using :wq! .

bottle-app

After save and closing the file, run this application with the command shown below.

$ python ~/projects/hello.py
Bottle v0.12.9 server starting up (using WSGIRefServer())...
Listening on http://0.0.0.0:8080/
Hit Ctrl-C to quit.

Now you can visit this application in your web browser by going to your IP address, followed by the port we chose to run on (8080), followed by the route we created (/hello):

http://your_servers_ip:8080/hello

Once you access the URL in you web browser, you will get its traffic on your command line terminal. You can stop the server at any time by typing Ctrl+c .

hello-world

Creating a Bottle Model:

Now in this portion of our program we are going to develop an advanced application with implementation of MVC principles to create a slightly more sophisticated application this time.

We’ll start with our model that handles the data storage. Bottle can easily implement a variety of back ends for data through the use of plugins. We will use an SQLite database file for our database, as its an extremely simple database designed for lightweight tasks.

Run below commands to install SQLite package followed by the Bottle plugin that will allow us to use these databases.

$ sudo apt-get install sqlite
$ pip install bottle-sqlite

Now we will create a Python file that will generate a SQLite database with some data as shown. Simply create a new file and put the following content in it.

$ vim ~/projects/picnic_data.py
import sqlite3
db = sqlite3.connect('picnic.db')
db.execute("CREATE TABLE picnic (id INTEGER PRIMARY KEY, item CHAR(100) NOT NULL, quant INTEGER NOT NULL)")
db.execute("INSERT INTO picnic (item,quant) VALUES ('eggs', 4)")
db.execute("INSERT INTO picnic (item,quant) VALUES ('cheese', 2)")
db.execute("INSERT INTO picnic (item,quant) VALUES ('mangoes', 30)")
db.execute("INSERT INTO picnic (item,quant) VALUES ('cake', 1)")
db.execute("INSERT INTO picnic (item,quant) VALUES ('fruit', 4)")
db.commit()

Here , in the first line we Import the SQLite package and then Execute a command that creates our table and inserts data and Finally, we commit the changes . Now save and close the file and execute the file, which will create a database file called picnic.db within our current directory as shown.

$ python ~/projects/picnic_data.py

Now if you run the ls command, you will that the database file has been created as shown.

bottle-sqlite-db

Creating a Bottle Container:

After database setup, now we are going to start and develop our main application which will mainly implement our controller functionality. It will also be the file that most closely resembles our first application.

Let’s create a new file called picnic.py to store our main application by placing the following contents in it.

$ vim ~/projects/picnic.py
import sqlite3
from bottle import route, run, template
@route('/picnic')
def show_picnic():
    db = sqlite3.connect('picnic.db')
    c = db.cursor()
    c.execute("SELECT item,quant FROM picnic")
    data = c.fetchall()
    c.close()
    output = template('bring_to_picnic', rows=data)
    return output
run(host='0.0.0.0', port=8080)

In this file, we added some additional modules that we haven’t used before and import the SQLite functionality. Then we define a route that matches the URL path /picnic and implements the function that connects to our database, gets our data from the table, and calls our view to render the page. In the end we have add our run command to run the actual server.

 

Creating a Bottle View:

After setting up the model and controller, the thing which left is to create view using Bottle’s built-in template engine. The application will search for a template matching the name given in the template function, ending with .tpl . This can either be in the project’s main directory, or in a directory called view.

Let’s create a file matching the one we called with the template function in the output line in the previous script and put the following code in it.

$ vim ~/projects/bring_to_picnic.tpl

bottle-view

In this file, we have mix HTML and programming but in simple format. It will use a loop to create a table, which we will populate with our model data. Save and close the file after placing the data in it and move to the next step.

Starting the Bottle Application:

Our Bottle’s application is ready , now we can start the program by calling Python on the main file.

$ python ~/projects/picnic.py
Bottle v0.12.9 server starting up (using WSGIRefServer())...
Listening on http://0.0.0.0:8080/
Hit Ctrl-C to quit.

Now open your web browser followed by the URL route we created using your server’s IP address.

http://your_servers_ip:8080/picnic

 

Now press ‘Ctrl+C’ to stop the application or Ctrl+Z to strongly stop signal. If you need to exit the virtual environment, you can type deactivate at any time.

 

Conclusion:

At the end of this article now you can build complex applications using a simple, bare-bones micro-framework like Bottle. We used simple examples so that you can take advantage of its more advanced functionality.

Bottle’s plugin system is also an important asset. Plugins are actively shared within the community and it is easy to implement more complex behavior through the plugin system. I hope you enjoyed reading the article and found this helpful in deploying Python Web Applications with the Bottle Micro Framework on Ubuntu 16.04. Do not forget to share your valuable comments and suggestions.

2017-09-29T12:48:54+00:00 September 29th, 2017|0 Comments

Leave A Comment