access/update global/shared defaultdict from different tornado.RequestHandler instances
<p>Is it safe to access/update a global <code>defaultdict</code> from different <code>RequestHandler</code> instances? E.g.</p>

<pre><code>GlobalMap = defaultdict(list)

class Event(tornado.web.RequestHandler):
    def get(self, unit):
        # This is where the access/modify might happen
        # The list.append() is just an arbitrary example
        GlobalMap[unit].append(datetime.utcnow()) 
        self.write(b'') 
</code></pre>

<p>If not, whatâs the proper way to do a lookup/store of keyed data between different <code>RequestHandler</code> instances?</p>

<p>In an async/threaded/multiprocess app, accessing global variables are as safe as you make them. As in, it's never really a good idea to have shared states. But for the most part it's fairly safe to access values from a global <code>dict</code> especially in an a single threaded async app.</p>

<p>On the other hand, eventually it will become unruly to house all <code>RequestHandler</code> classes in a single module. Having a dictionary as a data store will not be able scale out effectively. What <code>A. Jesse Jiryu Davis</code> was implying in his answer, is that the data you have in <code>GlobalMap</code> should be stored in some sort of database so that it can be shared.  There are a plethora of database solutions which "feel" alot like traditional <code>dict</code> objects such as <a href="https://motor.readthedocs.io/en/stable/" rel="nofollow">MongoDB</a> and Redis.</p>

<h1>Update</h1>

<p>You can also pass in additional parameters when you building your <code>Application</code> object. So in your main module you can do something like:</p>

<pre><code>GlobalMap = defaultdict(list)

class Event(tornado.web.RequestHandler):
    def initialize(self, shared_dict):
        self.shared_dict = shared_dict

app = Application([
    #...
    (r"/", Event, dict(shared_dict=GlobalMap))
])
</code></pre>

<p>Take a look at the <a href="http://www.tornadoweb.org/en/stable/guide/structure.html#the-application-object" rel="nofollow"><code>Application</code> docs</a> and the <a href="http://www.tornadoweb.org/en/stable/web.html#tornado.web.URLSpec" rel="nofollow"><code>URLSpec</code> docs</a>. I feel a bit foolish for not recalling this earlier. This will handle accessibility amongst Tornado apps, but not so much with other modules, in which case you would definitely need an external database.</p>

python python-3.x tornado defaultdict