Bottle:Python微框架完全指南
Bottle简介
Bottle是一个极简主义的Python微框架,专为构建Web应用和REST API而设计。整个框架仅由一个不到100KB的单一文件组成,是小型项目、原型开发、嵌入式系统和微服务的理想选择。Bottle无需外部依赖即可提供运行完整Web应用所需的所有组件。
Bottle的特点与优势
轻量级与简洁性
Bottle无需外部依赖,一条命令即可完成安装。框架仅包含一个文件,大大简化了部署和代码理解过程。
内置功能
- 内置HTTP开发服务器
- 自带SimpleTemplate模板引擎
- 支持WSGI用于生产环境部署
- 自动识别路由参数类型
- 处理JSON、表单、文件和Cookie
架构灵活性
Bottle兼容任何Python数据库库、模板引擎和WSGI服务器,可轻松集成到现有系统中。
安装与基本配置
安装Bottle
pip install bottle
创建第一个应用
创建文件app.py:
from bottle import route, run
@route('/')
def index():
return "Bottle 你好!"
@route('/hello/<name>')
def greet(name):
return f"你好,{name}!"
if __name__ == "__main__":
run(host='localhost', port=8080, debug=True)
启动应用
python app.py
应用将在http://localhost:8080上运行
路由与请求处理
基础路由
from bottle import route, get, post, put, delete
@route('/')
def home():
return "首页"
@get('/users')
def get_users():
return "用户列表"
@post('/users')
def create_user():
return "创建用户"
@put('/users/<id:int>')
def update_user(id):
return f"更新用户 {id}"
@delete('/users/<id:int>')
def delete_user(id):
return f"删除用户 {id}"
路由参数
Bottle支持多种参数类型:
@route('/user/<id:int>')
def user_by_id(id):
return f"用户ID:{id}"
@route('/article/<slug:path>')
def article_by_slug(slug):
return f"文章:{slug}"
@route('/price/<amount:float>')
def price(amount):
return f"价格:{amount}"
@route('/profile/<username:re:[a-zA-Z0-9_]+>')
def profile(username):
return f"个人资料:{username}"
处理查询参数
from bottle import request
@route('/search')
def search():
query = request.query.get('q', '')
category = request.query.get('category', 'all')
return f"搜索'{query}',分类'{category}'"
请求数据处理
表单处理
from bottle import request, post
@post('/submit')
def submit_form():
name = request.forms.get('name')
email = request.forms.get('email')
age = request.forms.get('age', type=int)
return f"收到数据:{name}, {email}, {age}"
JSON处理
from bottle import request, response
@post('/api/data')
def handle_json():
data = request.json
# 数据处理
result = {
'status': 'success',
'received': data,
'message': '数据'
}
response.content_type = 'application/json'
return result
模板引擎
使用SimpleTemplate
from bottle import route, view, template
@route('/hello/<name>')
@view('hello_template')
def hello(name):
return dict(name=name)
# 或直接使用template函数
@route('/greet/<name>')
def greet(name):
return template('<h1>你好,{{name}}!</h1>', name=name)
模板文件示例(hello_template.tpl)
<!DOCTYPE html>
<html>
<head>
<title>欢迎页面</title>
</head>
<body>
<h1>你好,{{name}}!</h1>
<p>欢迎使用Bottle框架。</p>
</body>
</html>
静态文件服务
from bottle import static_file
@route('/static/<filename:path>')
def serve_static(filename):
return static_file(filename, root='/path/to/static')
错误处理
from bottle import error
@error(404)
def not_found(error):
return "页面未找到"
@error(500)
def server_error(error):
return "服务器内部错误"
生产环境部署
使用Gunicorn部署
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8080 app:app
使用uWSGI部署
pip install uwsgi
uwsgi --http :8080 --wsgi-file app.py --callable app
总结
Bottle是一个功能强大且易于使用的Python微框架,适合快速开发小型Web应用和API。其轻量级设计、零依赖和简洁的API使其成为学习Web开发和构建原型项目的绝佳选择。无论是个人项目还是企业微服务,Bottle都能提供高效、灵活的解决方案。