【问题标题】:Run a function once on bottle.py startup在 bottle.py 启动时运行一次函数
【发布时间】:2013-01-04 16:46:56
【问题描述】:

我有一个瓶子应用程序,我最终不想在 apache 上部署(仅供参考,以防这很重要)。 现在我需要在瓶子应用程序启动后运行一次函数。我不能只将它放入路由函数中,因为即使还没有用户访问该站点,它也必须运行。

有什么最佳做法吗?

该函数启动一个 APScheduler 实例并向其添加一个作业存储。

【问题讨论】:

标签: python scheduling bottle


【解决方案1】:

这就是我所做的。

def initialize():
    //init whatever you need.
if __name__ == '__main__':
    initialize()
    @bottle.run(port='8080', yatta yatta)

【讨论】:

  • 这仅在您使用内置服务器时有效。否则它不会运行。
【解决方案2】:

老实说,您的问题只是同步与异步的问题。使用 gevent 轻松转换为微线程,然后分别启动每个微线程。如果您想等待 Web 服务器完成启动,您甚至可以在您的函数中或之前使用 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)

【讨论】:

    【解决方案3】:

    创建一个 APScheduler class

    查看同一站点中对象使用和创建的示例,因为它过于笼统,无法给出具体的示例来复制。

    我不知道this 是否有帮助。

    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
    

    无论如何,我仍在学习这些东西,这只是一个想法。

    【讨论】:

    • 实际上它是一个 python 脚本,它不会取消你的方法,但该脚本与瓶子应用程序本身交互。问题是我需要安排的功能也是瓶子应用程序的一部分,因此我无法运行与该应用程序隔离的调度程序。
    • 创建一个你启动时初始化的类,然后在需要时使用。
    • 我非常感谢您的努力,但这对我一点帮助都没有。我熟悉所有这些类和初始化的东西,但我仍然需要知道的是如何在瓶子运行方法之后调用任何东西(无论是初始化一些东西还是只是调用一个函数)而不将其放入路由函数中。它必须按照这个顺序,因为我不想在服务器启动之前定义函数(不知道为什么会这样)
    【解决方案4】:
    import threading
    import bottle
    
    def init_app():
        def my_function_on_startup():
            # some code here
            pass
        app = bottle.app()
        t = threading.Thread(target=my_function_on_startup)
        t.daemon = True
        t.start()
        return app
    
    
    app = init_app()
    
    @app.route("/")
    def hello():
        return "App is running"
    
    if __name__ == "__main__":
        bottle.run(app, host='localhost', port=8080, debug=True)
    

    【讨论】:

      猜你喜欢
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 2012-06-06
      • 1970-01-01
      相关资源
      最近更新 更多