tags:

views:

42

answers:

2

I was reading through the Flask doc - and came across this:

... For web applications it’s crucial to react to the data a client sent to the server. In Flask this information is provided by the global request object. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer are context locals ...

Now I understood context locals to be stuff like the with statement (certainly thats what the python 2.6 doc seems to suggest). Im struggling to see how this would allow you to have globally accessible vars that reside in a local namespace? How does this conceptually work?

Also: globals are generally considered filthy I take it, so why is this OK ?

+2  A: 

They are actually proxy objects to the real objects so that when you reference one you get access to the object for your current thread.

An example would be the request object. You can see this being set up in globlals.py and then imported into the __init__.py for flask.

The benefit of this is that you can access the request just by doing

from flask import request

and write methods like

@app.route('/')
def hello_world():
    return "Hello World!"

without having to pass the request around as a parameter.

This is making use of some of the reusable code libraries from Werkzeug.

mikej
Sorry if i'm being dense: but if i get this correctly they push the context onto a sort of 'stackframe' and then are able to appropriately route the attribute call to the correct linked object based on this stack?
Malang
If you grab a copy of the [source for Werkzeug](http://pypi.python.org/packages/source/W/Werkzeug/Werkzeug-0.6.2.tar.gz) and look in `local.py` you will see that the `Local` class basically uses a dictionary with the current thread ID as the key to store and retrieve the right objects transparently. This is the the limit of what I can deduce without setting up some tests to figure out what the code is doing.
mikej
I don't think a stack is necessary for the above. This is just a guess but the stack may just add an extra layer related to this comment in the documentation you linked to: *It does that in an intelligent way that one application can invoke another application without breaking.*
mikej
A: 

namespaces in python are basically dictionaries you could do

globals()['foo']=bar
mossplix
+1 good point :)
Malang