Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function once on bottle.py startup

I have a bottle app that I eventually wan't to deploy on apache (just fyi in case that's important). Now I need to run a function once after the bottle app is started. I can't just put it into a routed function because it has to run even if no user has accessed the site yet.

Any best pratice to do this ?

The function starts a APScheduler Instance and adds a jobstore to it.

like image 942
pypat Avatar asked Jan 21 '13 15:01

pypat


2 Answers

Here's what I do.

def initialize():
    //init whatever you need.
if __name__ == '__main__':
    initialize()
    @bottle.run(port='8080', yatta yatta)
like image 79
Tadgh Avatar answered Nov 14 '22 10:11

Tadgh


Honestly your problem is simply a sync vs async issue. Use gevent to easily convert to microthreads, and then launch each separately. You can even add a delay either in your function or before with gevent.sleep if you want to wait for the web server to finish launching.

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)
like image 1
eatmeimadanish Avatar answered Nov 14 '22 11:11

eatmeimadanish