4

In web.py i need to create a shared variable, for which multiple threads(requests) can read or write to that variable.

What is the preferred way, for this kind of a situation.

thanks.

4
  • 1
    Perhaps give a little more detail on what you're trying to accomplish. Commented Apr 15, 2011 at 13:39
  • You should say what kind and size of data that variable will contain, how sensitive is the data, and how often you will write to it and read from it. Commented Apr 15, 2011 at 13:40
  • sorry for missing info. read and write is very often to the variable (hundreds in second). so database is not an option. think of an integer. Commented Apr 15, 2011 at 13:46
  • memcached is ok. but for my case, running memcached is not an option. Commented Apr 15, 2011 at 13:52

2 Answers 2

2

I'm not sure this is really a web.py question, but we do this sort of thing all the time for process-wide caches (that is, dict caches that are shared by all request threads). We use web.py, but my example below should apply to any multi-threaded Python web server.

hotels.py:

cache = {}

def load_cache():
    """Load hotels into {id: data} dict cache."""
    rows = db.select('hotels')
    for row in rows:
        cache[row.id] = row

def get_hotel(hotel_id):
    """Get data for hotel with given ID, or return None if not found."""
    if not cache:
        raise Exception('hotels cache not loaded')
    return cache.get(hotel_id)

main.py:

import hotels

def main():
    hotels.load_cache()
    start_server()
Sign up to request clarification or add additional context in comments.

Comments

1

I find lots of code using this container: web.ctx

like

web.ctx.orm = scoped_session(sessionmaker(bind=engine))
web.ctx.session = web.config._session

u can init those in a function, then process them:

app.add_processor(web.loadhook(init_func))

Not sure it works or not for your scenario

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.