Skip to content

Instantly share code, notes, and snippets.

@davidreynolds
Created June 9, 2010 01:04
Show Gist options
  • Save davidreynolds/430894 to your computer and use it in GitHub Desktop.
Save davidreynolds/430894 to your computer and use it in GitHub Desktop.
"""
Provides an example on how to create a server script for blueberry.
"""
import os
import sys
from signal import SIGTERM
from optparse import OptionParser
from routes.middleware import RoutesMiddleware
from blueberry import web, config
from blueberry.deploy import start
from barly.config.environment import load_environment
def main():
usage = "Usage: %s [options] cmd\n" % sys.argv[0]
parser = OptionParser(usage=usage)
parser.add_option("--pidfile", dest="pidfile")
parser.add_option("-r", "--reload", dest="do_reload", action="store_true", default=False)
parser.add_option("-d", "--daemon", dest="daemonize", action="store_true", default=False)
options, args = parser.parse_args()
if not args:
sys.stderr.write("No arguments given.\n%s" % usage)
return
cmd = {'start': _start,
'stop': _stop}.get(args[0])
if cmd is None:
sys.stderr.write("Invalid command.\n%s" % usage)
return
# TODO: move config variables to .ini file
debug = True
load_environment(debug)
cmd(options)
def _start(options):
app = web.WSGIApplication(config['app']['debug'])
app = RoutesMiddleware(app, config['routes.map'])
try:
if options.daemonize:
from blueberry.utils.daemonize import become_daemon
become_daemon()
if options.pidfile:
try:
f = open(options.pidfile, "w")
f.write(str(os.getpid()))
finally:
f.close()
# start has to be called after becoming a daemon
start(app, reloader=options.do_reload)
except KeyboardInterrupt:
pass
def _stop(options):
if options.pidfile:
try:
f = open(options.pidfile, "r")
pid = int(f.read().strip())
except IOError:
# file doesn't exist
return
finally:
f.close()
os.kill(pid, SIGTERM)
os.unlink(options.pidfile)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment