Uri Laserson
Uri Laserson

Reputation: 2451

How do I load and cache data into a bottle.py app that's accessible in multiple functions without using global variables?

I have a bottle.py app that should load some data, parts of which get served depending on specific routes. (This is similar to memcached in principle, except the data isn't that big and I don't want the extra complexity.) I can load the data into global variables which are accessible from each function I write, but this seems less clean. Is there any way to load some data into a Bottle() instance during initialization?

Upvotes: 0

Views: 370

Answers (1)

Jay Choo
Jay Choo

Reputation: 1016

You can do it by using bottle.default_app
Here's simple example.

main.py (used sample code from http://bottlepy.org/docs/dev/)

import bottle
from bottle import route, run, template

app = bottle.default_app()
app.myvar = "Hello there!"  # add new variable to app

@app.route('/hello/<name>')
def index(name='World'):
    return template('<b>Hello {{name}}</b>!', name=name)

run(app, host='localhost', port=8080)

some_handler.py

import bottle

def show_var_from_app():
    var_from_app = bottle.default_app().myvar
    return var_from_app

Upvotes: 2

Related Questions