Python web framework

Dr. Huidae Cho
Institute for Environmental and Spatial Analysis...University of North Georgia

1   Web server gateway interface (WSGI)

2   Bottle

Install Bottle

pip install bottle

3   First web server

webapp.py

# import the bottle module and create a new namespace "bottle"
import bottle

# in this decoration pattern, we'll respond to a URL http://localhost:8080/hello/<name>
@bottle.route("/hello/<name>")
def hello(name):
    # when we respond to the URL, we'll pass Hello <name> content to the client
    return bottle.template("Hello {{name}}!", name=name)

# let's run an experimental server on port 8080 on this machine (localhost)
bottle.run(host="localhost", port=8080)

4   Using from import

webapp.py

# import only route, template, and run from the bottle module
from bottle import route, template, run

# in this decoration pattern, we'll respond to a URL http://localhost:8080/hello/<name>
@route("/hello/<name>")
def hello(name):
    # when we respond to the URL, we'll pass Hello <name> content to the client
    return template("Hello {{name}}!", name=name)

# let's run an experimental server on port 8080 on this machine (localhost)
run(host="localhost", port=8080)

5   Using template files

webapp.py

from bottle import route, template, run

@route("/hello/<name>")
def hello(name):
    return template("hello", name=name)

run(host="localhost", port=8080)

hello.tpl

<!doctype html>
<html>
<head>
<title>Hello {{name}}!</title>
</head>
<body>
Hello {{name}}!
</body>
</html>

6   Responding to multiple GET requests

webapp.py

from bottle import route, template, run

@route("/hello/<name>/<cls>")
def hello(name, cls):
    return template("hello", name=name, cls=cls)

@route("/bye/<name>")
def bye(name):
    return template("bye", name=name)

run(host="localhost", port=8080)

hello.py

<!doctype html>
<html>
<head>
<title>Hello {{name}}!</title>
</head>
<body>
<h1>Hello {{name}}!</h1>
<h2>Welcome to {{cls}}!</h2>
</body>
</html>

bye.tpl

<!doctype html>
<html>
<head>
<title>Bye {{name}}!</title>
</head>
<body>
Bye {{name}}!
</body>
</html>