Skip to main content

Making a web app with bottle and python tutorial series - part 3 - Creating a basic bottle application

Previous Part: Making a Bottle app with Python Tutorial Part 2 - Introduction to python Requests module
In this part you will be introduced to basic concepts in bottle framework and then we will extend these concepts in the further tutorials(parts). 

Pre-requisite 

Before we start using bottle framework we will have to either install the bottle framework or simply download the file to the working directory(The folder in which you are going to create the web app). 

If you are new to using command prompt then see the following video(13:25):


Installing on your computer
If you want to install the bottle, then open your command prompt, now you should see something like this:
Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. All rights reserved.

C:\Users\anivarth>
Next type the following after the '>':
C:\Users\anivarth>pip install bottle
That's it you are done, you have installed bottle on your computer and you can use it by importing it into your python scripts.

If you are new to pip then you can see this video(2:36) and you will be good to go!


Note: You can also use the virtual environment to install bottle. Please read the official documentation if you want to do so. Skip installing on virtual env(this Note!) if you are new to it.

If you are using other operating systems other than windows then please see 'using it directly without installing.'

If you know how to install bottle on other operating systems then please do help the community by contributing your tut here or comment in the comment box below.


Using it directly without installing
If you just want to use bottle.py without installing it on your computer you can also do so. You can do this because bottle is only a single file and you can import bottle as if you were importing a python script. Okay, now lets say you have created a folder for our web app with the name 'weave' and the folder structure is as follows:
weave
|--bottle.py
|
That's it now you will add your python script in this folder and you are ready to go.

Creating your first bottle web app and running it

Open your idle and open a new script window(ctrl+n) and type the following code and save it as weave.py:

from bottle import run, route

@route('')
@route('/')
def name():
    return 'My name is Anivarth Peesapati'

run(host='localhost', port=8080)
Now open the command prompt and 'cd' to your directory weave. In my case I have saved the folder on desktop. Then it(text in cmd.exe) will look like this:
C:\Users\anivarth>cd desktop
C:\Users\anivarth\Desktop>cd weave
After we have navigated to the folder we will execute the python script and the result will be like this:
C:\Users\anivarth\desktop\weave>python weave.py
Bottle v0.12.9 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.
After you see this go to http://localhost:8080/. You will find something like this:
bottle application localhost:8080
First bottle application 

So what has actually happened?

First we have imported run and route from the bottle module. 'run' which we have imported will start the server at the 'localhost'. 'route' decorator which we have used is for telling python when the user will type the url given in the parenthesis of the route then call the following function. Here in this case when the user calls either 'http://localhost:8080' or 'http://localhost:8080/' then the function 'name' will be initiated and the function will return the text 'My name is Anivarth Peesapati'. 

Hint: You can call 'run' without any parameters in the parenthesis and it will work. 

To stop the server hit ctrl+c . If you want to start it again then simply type python weave.py in command prompt and it will start the server.

Even though it is not compulsory for you know the decorators in python, but it is recommended that you know them. If you want to know decorators then you can skim through this article: Understanding python Decorators in 12 easy steps.

If you have observed, for every change you have made to the script you will have to hit ctrl+c(to stop the server) and again restart the server by typing python weave.py(start the server). There is a solution for this kind of problem in bottle. see the following code:

from bottle import run, route

@route('')
@route('/')
def name():
    return 'My name is Anivarth Peesapati'

run(reloader=True)
Now as we have added 'reloader=True', bottle will check if you have made any changes to the file 'weave.py' every now and then and will restart the server as soon as the changes are made. It is recommended not to use this in the production version.

Till now we have seen that we will define the url and the user will use the same url. But what if we had something like- the user can use his/her own url and they will be returned with data based on the url? Yes, don't worry we do have something called as dynamic url's in bottle. You can use that as follows:

from bottle import run, route

@route('/<name>')
@route('/<name>/')
def dynamic(name):
    return '<center><h1>Hello '+name+'</h1></center>'


run(reloader=True)
Now go to the url: http://localhost:8080/Anivarth, you will find something like this:
Generating dynamic urls with python bottle framework
Dynamic Url's with python Bottle framework
Try changing my name with your name and there should be a change on the website even.

Now what if you only wanted to return some data to url's containing only specific type of data type like for example in the above case if you only wanted to generate the data for 'str' data types and not for 'int' or 'float' or any others? Yes there is a hack with bottle framework to generate data only for specific data types in the url. It will look something like this:

from bottle import run, route

@route('/<number:int>') #return data only for int
@route('/<number:int>/')
def dynamic_number(number):
    return 'You have entered a number which is: '+str(number)


@route('/<num_float:float>') #return data for float
@route('/<num_float:float>/')
def dynamic_float(num_float):
    return 'The floating point you have entered is: '+str(num_float)

run(reloader=True)
Now after you will start the server, then open the following:

  1. http://localhost:8080/anivarth
  2. http://localhost:8080/123
You will see the change ;-). 


Also there are many other types which you can see from here: Dynamic Routes

Finally in this part we will see on how to use templates in bottle. i.e. How to output our data to a web page in a more efficient and effective manner.

Before we proceed further it is recommended that you know basics of HTML and CSS. Really basics not in depth :-) . If you don't know the basics(Like what is h1, h2, p, a tags?) then you can go through the following tutorials:

  1. HTML Tutorial from w3schools
  2. CSS Tutorials from w3schools
  3. HTML Basics Codecademy

If you have created a website then you will know what HTML & CSS documents are, but if we were to use the bottle then we will have to use '.tpl' file foramt instead of '.html'. Don't worry you will just change the file format from '.html' to '.tpl' and you are done. To understand better, lets say I am using the following HTML code for my project:

<!doctype html>
<html lang='en'>
 <head>
  <title>Radius of Circle - Bottle Tutorial series - weave</title>
  <meta charset='utf-8' />
 </head>
 <body>
  <h1>Hello world, This is Anivarth Peesapati!</h1>
  <h2>I welcome you to Radius of circle.</h2>
  <h3>You are reading bottle tutorial series.</h3>
  <h4>You are here to make a weather app called as Weave</h4>
  <h5>Hope you are finding the tutorial interesting!</h5>
  <h6>Have a great day :) !</h6>
  <p><a href="http://anivarth.pythonanywhere.com">Weave</a></p>
 </body>
</html>
Now save the above code as 'index.tpl' in the working directory. 

When you open the above code in your browser it should look something like this:
Making a basic web app with bottle.py framework and python
index.tpl when viewed as index.html
But how do you tell bottle to return the same template file? You will be doing it as follows:

from bottle import run, route, template

@route('/')
@route('')
def template_test():
    return template('index')

run(reloader=True)
What happened? You have imported run, route and template from bottle module. Next you have used the route decorator to define the url. We have created a function and named it 'template_test' which will be called when the user visits the url(http://localhost:8080 or http://localhost:8080/). Finally the function will return the template which in this case is 'index.tpl'. Remember that specifying the file extension '.tpl' is optional.

Have a look at this page if you are not clear with this: Templates - Bottle 

We can also change the content of the template file based on the user input and many other cool things can be done using bottle. We will see a few of them in the next part(Part 4) so that you can create web apps on the go! See you there!

I have tried to explain each and every part in this tutorial in such a way that it is easy for everyone to understand. But if you didn't understand anything or have any doubt please do comment in the comment box below or contact me. I will for sure help you asap. You can contact me from here: Contact me.

Please comment on how I can improve this article in such a way that everyone will be comfortable reading it. Also comment in the comment box below if I have made any typo or any mistake.

Thank you. Have a great day :) !

Popular posts from this blog

Problem 60 Project Euler Solution with python

Prime pair sets The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property. Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime. This problem is j u st a brute force problem. If you have come here because you don't know the limit upto which you will h ave to gener ate the prime numbers t hen go ahe ad and t r y with 10,000 . When I first start ed solving the problem I chose 1 million(beca use most of the problem s on project E uler have this limit ), but it took very long for the computer to fin d the solution. After searching on the internet then I found many people choosing 10, 000 so I have changed my in put f rom 1 million to 10000 and the output was f ast. He

Making a quiz web app with python and flask

Edit : When you are creating a web app with h tml templates, then y ou will have to sa ve the html file in templates folder in the Current Wor ki ng Directory( CWD). If you save the file in the C W D directl y you will get a TemplateNotFound error. Thank you Udhay for pointing it out.   In this post we will create a quiz website using python . I will be using the flask framework . After reading this tutorial you will learn form submission , flask templates , python code in flask templates , shuffling the questions and options with the random module and few others.  Please note that this tutorial is not big as it seems to be. Some of the code has been rewritten to maintain consistency and also font size is somewhat big so that your eyes won't get stressed reading this tutorial. Also the content has not occupied the full width of the page. In this tutorial I am assuming that you are having a very basic understanding of the flask framework . Please refer the documentation

Add/Embed SVG to Blogger website

In this post I will tell you my method(trick) of adding SVG images in a blogger website or blog. Before starting , the first thin g I am assu m ing is that you are aware of SVG if you are here. If not please see S calable V ec tor G raphics Recently when I tried to embed a SVG image for a post on pygal, I tried uploading the SVG file and blogger Image uploader came up with an error, because of which I had to find some other way.  SVG File upload Error in Blogger  I started sea rc hing Google " Embed SVG in Blogger " . I found blogorrhea , w h ich gave some i nformatio n on add ing SVG directly as a markup , which worked , but I faced another problem using this . Also th is guy has used lot of Javascript which was confusin g for me, being new to using SVG.   So I first t houg ht of learning on h ow to embed SVG in HTML and t his on e worked out. Actually we can embed SVG in HTML i n following ways: Using Object tag Using Iframe tag Using embed tag Us