Bottle Overview
Bottle is a fast, simple, and lightweight web framework for building web applications using Python.
It is designed to be easy to use, yet powerful enough to handle complex tasks. Bottle follows the minimalist philosophy, providing only the essential tools and features needed to develop web applications.
In this tutorial, we will explore the history, features, and examples of the Bottle web framework.
History
Bottle was created by Marcel Hellkamp in 2010 as a micro web framework for Python. It was inspired by other micro frameworks such as Flask and Sinatra. Since its inception, Bottle has gained popularity due to its simplicity, speed, and ease of use.
Features
Routing
One of the key features of Bottle is its routing system. It allows you to map URLs to Python functions or methods, making it easy to define the behavior of your web application. Here's an example of a simple route:
from bottle import route, run
@route('/')
def index():
return "Hello, World!"
run(host='localhost', port=8080)
In this example, the @route('/') decorator maps the root URL to the index function. When a user visits the root URL (http://localhost:8080/), the function is called and the string "Hello, World!" is returned as the response.
Templating
Bottle includes a built-in template engine that allows you to separate the logic and presentation of your web application. You can use templates to generate dynamic HTML pages by inserting data into predefined placeholders. Here's an example:
from bottle import route, run, template
@route('/greeting/<name>')
def greeting(name):
return template('Hello, {{name}}!', name=name)
run(host='localhost', port=8080)
In this example, the greeting function takes a name parameter from the URL and passes it to the template as the name variable. The template engine replaces {{name}} with the value provided, resulting in a personalized greeting.
Request Handling
Bottle provides convenient methods for handling HTTP requests. You can access request data such as headers, query parameters, and form data easily. Here's an example:
from bottle import route, run, request
@route('/login')
def login():
username = request.query.get('username')
password = request.query.get('password')
# Perform login logic here
return "Logged in successfully"
run(host='localhost', port=8080)
In this example, the login function retrieves the username and password from the query parameters of the URL. It can then use this data to perform the necessary login logic and return a response.
Middleware
Bottle supports middleware, which allows you to modify the request and response objects before they reach your route handlers. This feature is useful for tasks such as authentication, logging, and error handling. Here's an example:
from bottle import route, run, request, response
def authentication_middleware(callback):
def wrapper(*args, **kwargs):
# Perform authentication logic here
if not authenticated:
response.status = 401
return "Unauthorized"
return callback(*args, **kwargs)
return wrapper
@route('/protected')
@authentication_middleware
def protected_route():
return "You have access to this protected route"
run(host='localhost', port=8080)
In this example, the authentication_middleware function wraps the callback function with additional logic to perform authentication. If the user is not authenticated, a 401 Unauthorized status code is returned.
Examples
Todo List Web Application
Here's an example of a simple Todo List web application using Bottle:
from bottle import route, run, template, request
todos = []
@route('/')
def index():
return template('index', todos=todos)
@route('/add', method='POST')
def add_todo():
todo = request.forms.get('todo')
todos.append(todo)
return template('index', todos=todos)
run(host='localhost', port=8080)
In this example, the application displays a list of todos and allows users to add new todos. The index route renders the index template, passing the todos list as a variable. The add_todo route handles the form submission and adds the new todo to the list.
REST API
Bottle can also be used to create RESTful APIs. Here's an example of a simple API for managing tasks:
from bottle import route, run, request, response
tasks = []
@route('/tasks', method='GET')
def list_tasks():
return {'tasks': tasks}
@route('/tasks', method='POST')
def create_task():
task = request.json.get('task')
tasks.append(task)
response.status = 201
return {'message': 'Task created'}
run(host='localhost', port=8080)
In this example, the /tasks endpoint supports GET and POST methods. The list_tasks function returns a JSON response containing the list of tasks. The create_task function receives a JSON payload containing the task data, adds it to the list, and returns a success message.
For more information and documentation, you can visit the official Bottle website: https://bottlepy.org/