Your First Bottle Website
Writing the Code
Below is the code we will write:
from bottle import route, run
@route('/')
def hello():
return "Hello World!"
run(port=8080)
Running the Code
Run the code as you would run any other Python program. Once you run it, when you go to localhost:8080, you should see Hello World! displayed on the webpage.
Code Breakdown
Now, let's break down the code we just wrote.
On the first line, we have
from bottle import route, run
We do this to import a couple of different functions from the bottle
module we installed in the last tutorial. The run
function is used to run our server and the route
function is used to create routes for our server.
After, we have
@route('/')
def hello():
return "Hello World!"
Notice how this starts with
@route('/')
This is called a decorator function, meaning that it modifies the hello
function. In this case, it makes the hello
function a route for our page. For the route
function, we need to pass in a route for Bottle to use. The /
is the home page for our server.
After that, we define a function called hello
. When we call this function, it returns the text Hello World!. When we visit the home page of our site, we will se the text Hello World!. Bottle will run this function and display whatever text it returns. We can also put HTML code in the returned string. For example, try putting <h1>Hello!</h1>
. By running this code, we see Hello! displayed on the webpage as a heading (larger than regular text). We can also put HTML in templates, as we will learn in another tutorial.
Finally, we have
run(port=8080)
This runs our website and the Bottle server. We previously already imported run
from bottle
, so now we can use it. In the run
function, we have port=8080
. By default our server will run on localhost
with the default port, but in our case, we set the port to 8080
, so we can go to localhost:8080 to view our code.