I have a simple Bottle app which stores its configuration in a text file. Naturally, I need the config to be available in almost every handler of the app, and I want it to be reloaded on every request.
In Flask I could load the config file into开发者_Go百科 a ConfigParser
instance in before_request
and put a reference to it into an attribute of the g
object, just as described in the Flask documentation as a way of connecting SQLite. The g
object would then be available in every handler:
@app.before_request
def before_request():
g.config = load_config()
@app.route('/')
def index():
param = g.config.get(...)
...
In Bottle, on the other hand, thread locals are considered a bad thing, and the suggested way of storing the DB connection is to write a plugin which analyzes the handlers for signatures using clever tricks. And while the problem is already solved for SQLite, it is not in case of some other arbitrary per-request data.
To be frank, I can't believe I'm supposed to write 60 lines of code to do such a simple task, so I guess I must be missing something.
Any ideas?
Since you want it reloaded every single request, why not just use a function?
def get_config():
with open('config.json') as f:
return json.load(f)
@route('/')
def index():
config = get_config()
return 'Welcome to %s' % config['site_name']
If you wanted to wrap that into a plugin it's fairly simple:
def config_plugin(callback):
def wrapper(*args, **kwargs):
kwargs['config'] = get_config()
return callback(*args, **kwargs)
return wrapper
install(config_plugin)
@route('/')
def index(config):
return 'Welcome to %s' % config['site_name']
精彩评论