laitimes

bottle, a fantastic Python library!

author:Not bald programmer
bottle, a fantastic Python library!

Hello everyone, today I would like to share with you a magical Python library - bottle.

Github address: https://github.com/bottlepy/bottle

Python, as a popular programming language, has a rich web development framework. Among them, Bottle, as a lightweight web framework, has been widely welcomed. This topic describes the installation, features, basic functions, advanced functions, and practical application scenarios of the Bottle library.

Installation

The Bottle library can be installed via pip:

pip install bottle           

characteristic

  1. Simple and easy to use: Bottle's design is simple and straightforward, with a low learning curve, making it suitable for rapid development.
  2. Built-in HTTP server: Bottle comes with a lightweight HTTP server, which is convenient for quickly setting up a development environment.
  3. Routing function: The routing function is supported, and you can easily define URL mapping to the corresponding processing function.
  4. Template engine: Supports a variety of template engines, such as Jinja2 and Mako, to facilitate page rendering.

Basic functions

1. Routing function

Bottle provides a powerful routing function, which can map URLs to the corresponding processing functions to implement the distribution and processing of requests.

from bottle import route, run

@route('/')
def index():
    return 'Hello, World!'

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

The example code above defines a route that, when the root path is accessed, executes the index function and returns 'Hello, World!'.

2. Request the parameters

Bottle can easily obtain the parameters in the request, including the query parameters in the GET request and the form data in the POST request.

from bottle import route, run, request

@route('/hello')
def hello():
    name = request.query.get('name', 'Guest')
    return f'Hello, {name}!'

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

The above example code defines a route/hello, uses the request.query.get method to get the query parameter named name, and returns the corresponding greeting.

3. Static File Service

Bottle can be used to provide static file services, such as CSS, JavaScript, images, etc., to facilitate the display and reference of front-end pages.

from bottle import route, static_file, run

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

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

The above example code defines a static file service route/static/<filename:path> to return static files from the specified directory to the client.

4. Template rendering

Bottle supports a variety of template engines, such as Jinja2, Mako, etc., which can easily render pages.

from bottle import route, run, template

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

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

The above example code uses the template engine, passing the parameter name in the route and rendering it in the template file hello_template.tpl.

Advanced features

1. Middleware

Bottle allows users to define middleware to handle requests and responses, enabling preprocessing, filtering, and enhancement of requests.

from bottle import Bottle, run, request

app = Bottle()

@app.middleware('request')
def check_auth():
    token = request.headers.get('Authorization')
    if not token or token != 'Bearer secret_token':
        return {'error': 'Unauthorized'}, 401

@app.route('/protected')
def protected_route():
    return 'Protected Resource'

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

The above example code defines a middleware function check_auth to check the Authorization information in the request header to protect the access of route/protected.

2. Plugins

Bottle's plug-in system allows developers to extend the framework's functionality, such as logging, performance monitoring, database connections, and more.

from bottle import Bottle, run
from bottle_sqlite import SQLitePlugin

app = Bottle()
plugin = SQLitePlugin(dbfile='/path/to/database.db')
app.install(plugin)

@app.route('/users')
def list_users(db):
    users = db.execute('SELECT * FROM users').fetchall()
    return {'users': users}

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

The above example code uses the SQLite plugin to interact with the SQLite database, which can be injected with database objects via parameters in the route.

3. Asynchronous processing

Bottle supports asynchronous request processing, which can be used to improve performance and concurrency.

from bottle import Bottle, run, request
import asyncio

app = Bottle()

@app.route('/async')
async def async_route():
    await asyncio.sleep(1)
    return 'Async Response'

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

The example code above defines an asynchronous route/async, declares an asynchronous function with the async def keyword, and implements asynchronous await using asyncio.sleep.

Practical application scenarios

The Python Bottle library has a wide range of uses in real-world applications and can be used to develop various types of web applications. Here are some common real-world use cases, with corresponding sample code:

1. Small web applications

Bottle is ideal for building small web applications, such as personal blogs, simple online tools, or API services.

from bottle import Bottle, run

app = Bottle()

@app.route('/')
def home():
    return 'Welcome to My Website!'

@app.route('/about')
def about():
    return 'About Us Page'

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

2. RESTful API services

Bottle makes it easy to build RESTful-style API services that handle a variety of HTTP requests and return data in JSON format.

from bottle import Bottle, run, request, response

app = Bottle()

@app.route('/api/users', method='GET')
def get_users():
    # 查询数据库或其他数据源,返回用户列表
    users = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]
    return {'users': users}

@app.route('/api/users', method='POST')
def add_user():
    # 从请求中获取用户信息,添加到数据库,并返回新用户信息
    user_data = request.json
    # 添加用户到数据库的逻辑
    new_user = {'id': 3, 'name': 'Charlie'}  # 示例数据
    response.status = 201  # Created
    return new_user

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

3. The web interface is separated from the back-end logic

Bottle can be used to separate the front-end and back-end logic, the front-end is responsible for displaying the interface, and the back-end handles business logic and data interaction.

from bottle import Bottle, run, static_file, request

app = Bottle()

@app.route('/')
def home():
    return static_file('index.html', root='static')

@app.route('/submit', method='POST')
def submit_form():
    data = request.forms.get('data')
    # 处理表单数据的逻辑
    return 'Form submitted successfully'

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

4. Rapid prototyping of web services

Bottle provides a quick and easy way to rapidly prototype web services, validate ideas and test them functionally.

from bottle import Bottle, run, request, response

app = Bottle()

@app.route('/api/analyze', method='POST')
def analyze_data():
    data = request.json
    # 数据分析逻辑
    result = {'analysis': '...'}  # 示例结果
    return result

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

summary

The Python Bottle library is a lightweight, easy-to-use web framework for rapid development of small web applications and API services. It provides a simple routing mechanism, a template engine, and a lightweight HTTP server, making the development process efficient and flexible. Through the introduction of this article, you can learn about the installation, features, basic functions, advanced functions and practical application scenarios of the Bottle library, and attach detailed sample code to help you better get started and apply the library. Whether you're building a personal blog, a RESTful API service, or rapid prototyping, the Python Bottle library is a tool worth trying out for a variety of web development needs.