目录
Bottle 是一个轻量级的 Python Web 框架,它使用简单,易于上手,并且不需要任何外部依赖。下面将介绍 Bottle 的简单使用和一些常用的 API。
简单使用
安装Bottle
pip install bottle
创建一个简单的 Web 应用
from bottle import route, run, template
@route('/')
def index():
return "Hello, World!"
@route('/hello/<name>')
def hello(name):
return f"Hello, {name}!"
# 运行应用
run(host='localhost', port=8080)
定义了两个路由:
- 第一个路由
'/'
对应于根 URL,返回 "Hello, World!"。- 第二个路由
'/hello/<name>'
是一个带有动态参数的路由,其中<name>
是一个占位符,你可以通过函数参数name
访问它。
run()
函数用于启动应用服务器,你可以指定host
和port
参数来改变服务器的监听地址和端口。
常用 API
定义路由
route(path, method='GET', callback=None, name=None, apply=None, skip=None)
@route('/')
def index():
return "Index Page"
启动 Web 服务
run(host='localhost', port=8080, server='wsgiref', **kwargs)
run(host='0.0.0.0', port=80)
获取请求头、参数
request
一个全局对象,表示当前的 HTTP 请求。你可以从中获取请求头、参数等信息。
from bottle import request
@route('/greet')
def greet():
name = request.query.name # 获取查询参数
return f"Hello, {name}!"
设置响应头、状态码
response
一个全局对象,表示当前的 HTTP 响应。你可以设置响应头、状态码等信息。
from bottle import response
@route('/setheader')
def set_header():
response.set_header('X-Custom-Header', 'Value')
return "Header has been set"
渲染模板
template(filename, **kwargs)
渲染一个模板文件,并返回渲染后的结果。
from bottle import template
@route('/template')
def render_template():
return template('mytemplate', name='World')
静态文件路由
static_file(filename, root, mimetype='auto', download=False)
为静态文件提供路由。
@route('/static/<filename:path>')
def serve_static(filename):
return static_file(filename, root='./static')
重定向
redirect(url, code=None)
重定向到另一个 URL。
from bottle import redirect
@route('/redirect')
def do_redirect():
redirect("/new-location")
中止请求
abort(code=500, text='Unknown Error: Application aborted.')
中止请求并返回指定的 HTTP 状态码和文本。
from bottle import abort
@route('/error')
def show_error():
abort(404, 'Not Found')
安装插件扩展
install(plugin)
安装一个插件来扩展框架的功能。
from bottle import install
from someplugin import SomePlugin
install(SomePlugin())
定时任务
threading
+time
实现定时任务
Bottle 本身并不直接提供定时任务(定时执行某些操作)的功能。但是,可以结合使用 Python 的标准库
threading
和time
来实现定时任务。下面是一个使用 Bottle 和threading
创建简单定时任务的例子
from bottle import route, run, template
import threading
import time
# 这是一个定时任务的函数
def my_scheduled_task():
while True:
# 这里是你要定时执行的操作
print("执行定时任务...")
# 假设我们每隔5秒执行一次
time.sleep(5)
# 创建一个守护线程来运行定时任务
task_thread = threading.Thread(target=my_scheduled_task, daemon=True)
task_thread.start()
# 定义一个简单的路由
@route('/')
def index():
return "Hello, World!"
# 运行Bottle应用
run(host='localhost', port=8080)
my_scheduled_task
函数是一个无限循环,每隔5秒钟执行一次打印操作。我们将这个函数放入一个守护线程(daemon thread)中,这意味着当主程序(在这个例子中是 Bottle 服务器)退出时,这个线程也会自动退出。请注意,这种方式并不是最优的定时任务解决方案,特别是在生产环境中。这是因为它将定时任务与 Web 服务器线程绑定在一起,如果 Web 服务器停止,定时任务也会停止。
APScheduler
如果想要一个更专业、更健壮的定时任务解决方案,可以考虑使用
APScheduler
。下面是一个使用APScheduler
在 Bottle 应用中添加定时任务的例子:
安装 APScheduler
:
pip install apscheduler
使用
APScheduler
的BackgroundScheduler
,它会在后台运行定时任务,而不会干扰你的 Web 服务器线程。这种方式更适合生产环境,因为它提供了更多的配置选项和更好的可靠性。
import atexit
from bottle import route, run
from apscheduler.schedulers.background import BackgroundScheduler
# 初始化一个后台调度器
scheduler = BackgroundScheduler()
# 添加一个定时任务,每隔5秒执行一次
scheduler.add_job(func=lambda: print("执行定时任务..."), trigger='interval', seconds=5)
# 开始调度器
scheduler.start()
# 定义路由
@route('/')
def index():
return "Hello, World!"
# 注册atexit钩子, 该函数会在Python解释器终止时执行
atexit.register(lambda: scheduler.shutdown())
# 运行Bottle应用
run(host='localhost', port=8080)