Skip to content

Instantly share code, notes, and snippets.

@lae
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lae/10248212 to your computer and use it in GitHub Desktop.
Save lae/10248212 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import yaml
from datetime import datetime as dt
import json
import re
import collections
import bottle
from bottle import HTTPError, request, response
class Donate(object):
""" Main application that serves as a hypervisor to Bottle. """
def __init__(self):
# Default Settings. You can place overrides in config.yaml.
# 'bottle_run' settings are only used when executed standalone.
self.config = {
'bottle_run': {
'host': 'localhost',
'debug': True,
'port': 9002
}
}
# Overwrite settings if a config file exists.
try:
cfg = open('config.yaml')
except IOError as e:
print("I/O Error %s, %s (%s)" % (e.errno, e.strerror, e.filename),
"\nContinuing with default configuration.")
cfg = ''
if cfg:
try:
self.config.update(yaml.load(cfg))
except Exception:
print(e + "\nQuitting because I could not properly interpret",
"config.yaml; check that your syntax is correct.")
exit(1)
finally:
cfg.close()
# Assign this object to the first app in Bottle's AppStack().
self.app = bottle.Bottle()
# Setup the routes to be handled by this object.
self.install_routes(self.app)
# Assign most common "error" routes to a custom error handler.
errors = {sc: self.error_page for sc in range(400, 415)}
errors[500] = self.error_page
self.app.error_handler = errors
if __name__ == '__main__':
# Run app using bottle_run settings if executed standalone.
sb = []
for k, v in self.config['bottle_run'].items():
if isinstance(v, str):
sb.append("%s='%s'" % (k, v))
else:
sb.append("%s=%s" % (k, v))
print("Started:", str(dt.now()))
eval("self.app.run({0})".format(', '.join(sb)))
def error_page(self, e):
""" Return JSON documents when the application returns an HTTPError. """
response.content_type = 'application/json'
return dumps({'status_code': e._status_code, 'message': e.body})
def balancedshit(self):
do something
def install_routes(self, b):
b.route('/balance', 'POST', self.balancedshit)
donate = Donate()
app = donate.app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment