Bottle 应用程序中的长 运行 后台任务
Long running background task in a Bottle application
我一直在寻找一种方法来 运行 在 Python Bottle 应用程序中执行连续的后台任务,同时使用 Gevent 处理请求:
from gevent import monkey; monkey.patch_all()
from time import sleep
from bottle import route, run
# run_background_function()
# ^^^^ starts a single background task that runs every few seconds
# and continues for the life of the whole Bottle application.
@route('/simple-request')
def simple_request():
# a simple function that returns a rendered page and
# is capable of serving multiple requests
return rendered_page()
run(host='0.0.0.0', port=8080, server='gevent')
到目前为止,我已经阅读了许多 Whosebug 线程和 7 个完整教程,包括 Gevent、threading、celery、rabbitmq、redis,但不知道我应该使用什么来实现这种能力。 Celery、RabbitMQ 和 Redis 对于 运行 完成这个后台任务似乎都异常困难和矫枉过正,而且如果可能的话,我更愿意使用 Python 标准库中的选项。
到目前为止,我发现的教程都是从非常基础的开始,然后突然跳到包括第 3 方库、套接字、特定 Web 框架等。有没有办法仅在 Python 线程模块上执行此操作?
你可以用 multiprocessing
来做到这一点:
from multiprocessing import Queue, Process
def processor():
setproctitle('%s - processor ' % (__file__,))
while True:
time.sleep(1)
do_stuff()
my_processor = Process(target=processor)
我一直在寻找一种方法来 运行 在 Python Bottle 应用程序中执行连续的后台任务,同时使用 Gevent 处理请求:
from gevent import monkey; monkey.patch_all()
from time import sleep
from bottle import route, run
# run_background_function()
# ^^^^ starts a single background task that runs every few seconds
# and continues for the life of the whole Bottle application.
@route('/simple-request')
def simple_request():
# a simple function that returns a rendered page and
# is capable of serving multiple requests
return rendered_page()
run(host='0.0.0.0', port=8080, server='gevent')
到目前为止,我已经阅读了许多 Whosebug 线程和 7 个完整教程,包括 Gevent、threading、celery、rabbitmq、redis,但不知道我应该使用什么来实现这种能力。 Celery、RabbitMQ 和 Redis 对于 运行 完成这个后台任务似乎都异常困难和矫枉过正,而且如果可能的话,我更愿意使用 Python 标准库中的选项。
到目前为止,我发现的教程都是从非常基础的开始,然后突然跳到包括第 3 方库、套接字、特定 Web 框架等。有没有办法仅在 Python 线程模块上执行此操作?
你可以用 multiprocessing
来做到这一点:
from multiprocessing import Queue, Process
def processor():
setproctitle('%s - processor ' % (__file__,))
while True:
time.sleep(1)
do_stuff()
my_processor = Process(target=processor)