在bottle.py启动时运行一次函数
我有一个瓶子应用,最终想把它放到Apache上运行(顺便提一下,这可能很重要)。
现在我需要在瓶子应用启动后运行一个函数一次。我不能把这个函数放在路由的函数里,因为即使没有用户访问网站,它也必须运行。
有没有什么好的做法来实现这个呢?
这个函数会启动一个APScheduler实例,并为它添加一个任务存储。
4 个回答
0
创建一个 APScheduler 的 类。
可以去这个网站看看对象的使用和创建的例子,因为这里太笼统了,没法给出一个具体的例子让你直接复制。
我不知道 这个是否有帮助。
class Shed(object):
def __init__(self): # this to start it
# instruccions here
def Newshed(self, data):
# Call from bottle
# more methods ...
...
# init
aps = Shed() # this activates Shed.__init__()
...
# in the @router
x = aps.Newshed(data) # or whatever
总之,我还在学习这些东西,这只是一个想法。
1
老实说,你的问题就是同步和异步的区别。你可以使用gevent这个工具,轻松地把你的程序转换成微线程,然后分别启动每一个线程。如果你想等到网络服务器启动完成后再执行,可以在你的函数里或者之前加个延迟,使用gevent.sleep
就可以了。
import gevent
from gevent import monkey, signal, spawn, joinall
monkey.patch_all()
from gevent.pywsgi import WSGIServer
from bottle import Bottle, get, post, request, response, template, redirect, hook, abort
import bottle
@get('/')
def mainindex():
return "Hello World"
def apScheduler():
print "AFTER SERVER START"
if __name__ == "__main__":
botapp = bottle.app()
server = WSGIServer(("0.0.0.0", 80), botapp)
threads = []
threads.append(spawn(server.serve_forever))
threads.append(spawn(apScheduler))
joinall(threads)
1
我这样做。
def initialize():
//init whatever you need.
if __name__ == '__main__':
initialize()
@bottle.run(port='8080', yatta yatta)