Introduction to Bottle Web Framework - Python


Python has made a name for itself as a flexible language in the wide field of web development. Its wide selection of frameworks makes it easier to create reliable web apps. Bottle, a micro-web framework made specifically for creating web APIs, is one such framework. The Bottle web framework will be introduced in this post along with several useful Python examples.

Understanding Bottle: A Micro Web Framework

Bottle is a Python web framework that is quick, light, and easy to use. It is ideal for creating straightforward personal applications, experimenting, and learning the fundamentals of developing online applications. Over the WSGI standard, Bottle offers support for routing, templates, utilities, and fundamental abstractions.

Setting Up Bottle

Bottle must be installed before we can move on to the examples. Running the upcoming pip command will do it.

pip install bottle

Dive into Practical Examples

To further comprehend Bottle's characteristics, let's look at some real-world usage scenarios.

Example 1: Creating a Basic Application

Let's start by building a simple Bottle application. The only route for this application will reply to HTTP GET queries at the root URL ("/").

from bottle import Bottle, run

app = Bottle()

@app.route('/')
def home():
   return "Welcome to my Bottle application!"

run(app, host='localhost', port=8080)

Simply save the script and launch Python to execute this application. You can view the welcome message by opening your web browser and going to http://localhost:8080.

Example 2: Adding More Routes and HTTP Methods

More routes can be easily added, and Bottle makes it simple to react to various HTTP methods. The following illustration exemp

from bottle import Bottle, run, request

app = Bottle()

@app.route('/')
def home():
   return "Welcome to my Bottle application!"

@app.route('/hello/<name>', method='GET')
def hello(name):
   return f"Hello, {name}!"

@app.route('/login', method='POST')
def login():
   username = request.forms.get('username')
   password = request.forms.get('password')
   return f"Hello, {username}, your password is {password}."

run(app, host='localhost', port=8080)

In this case, two additional routes were introduced. The dynamic route /hello/name> grabs a portion of the URL as a parameter. In response to HTTP POST requests, the /login route reads information from the request body.

Example 3: Using Templates

You can create dynamic HTML answers using Bottle's built-in support for templates. Here's an illustration:

from bottle import Bottle, run, template

app = Bottle()

@app.route('/')
def home():
   return "Welcome to my Bottle application!"

@app.route('/hello/<name>', method='GET')
def hello(name):
   return template("<h1>Hello, {{name}}!</h1>", name=name)

run(app, host='localhost', port=8080)

In this instance, we construct an HTML response for the /hello/name> route using the template function. This function creates a string from a template string and a collection of keyword parameters by replacing placeholder characters (like "name") with the appropriate argument values.

Example 4: Serving Static Files

Serving static files like photos, CSS files, or JavaScript files is made simple using Bottle. How to achieve this is demonstrated by the example below:

from bottle import Bottle, run, static_file

app = Bottle()

@app.route('/')
def home():
   return "Welcome to my Bottle application!"

@app.route('/static/<filename>')
def serve_static_file(filename):
   return static_file(filename, root='/path/to/your/static/files')

run(app, host='localhost', port=8080)

The /static/filename> route in this illustration serves static files from the specified directory. The path to the directory holding your static files should be substituted with /path/to/your/static/files.

Example 5: Handling Errors

For various HTTP status codes, custom error pages can be defined in Bottle. Defining a personalised 404 error page is as follows −

from bottle import Bottle, run, abort

app = Bottle()

@app.route('/')
def home():
   return "Welcome to my Bottle application!"

@app.route('/fail')
def fail():
   abort(404, "Page not found")

@app.error(404)
def error404(error):
   return "The page you are looking for does not exist."

run(app, host='localhost', port=8080)

In this case, visiting http://localhost:8080/fail will result in a 404 error and display the customised error page.

Example 6: Using Bottle with a Database

Database integration is simple for Bottle. One may see a straightforward Bottle application using SQLite in the example below:

from bottle import Bottle, run, template, request
import sqlite3

app = Bottle()

@app.route('/')
def home():
   conn = sqlite3.connect('test.db')
   c = conn.cursor()
   c.execute("SELECT name FROM users")
   users = c.fetchall()
   return template("Home page. Users: {{users}}", users=users)

@app.route('/add_user', method='POST')
def add_user():
   conn = sqlite3.connect('test.db')
   c = conn.cursor()
   name = request.forms.get('name')
   c.execute("INSERT INTO users (name) VALUES (?)", (name,))
   conn.commit()
   return "User added."

run(app, host='localhost', port=8080)

In this illustration, a list of users from the "users" table in the SQLite database "test.db" is shown on the home page. A new user is added to the database via the /add_user route.

These illustrations show how adaptable and versatile the Bottle framework is. Bottle is a useful toolkit for Python web development that has a compact footprint and an intuitive UI. Bottle is a great option for your Python web framework whether you're creating a straightforward online application or a sophisticated RESTful API.

Conclusion

Bottle is a simple and effective Python tool for creating web apps. Its ease of use and lightweight construction make it a great option for beginners and programmes that need quick execution and little overhead.

The Bottle web framework was introduced and some of its key features were covered in this post using useful Python examples.

Updated on: 17-Jul-2023

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements