Converting Bottle FORMSDICT to a Python dictionary (in a thread safe way) Converting Bottle FORMSDICT to a Python dictionary (in a thread safe way) json json

Converting Bottle FORMSDICT to a Python dictionary (in a thread safe way)


Your code is thread safe. I.e., if you ran it in a multithreaded server, it'd work just fine.

This is because a multithreaded server still only assigns one request per thread. You have no global data; all the data in your code is contained within a single request, which means it's within a single thread.

For example, the Bottle docs for the Request object say (emphasis mine):

A thread-local subclass of BaseRequest with a different set of attributes for each thread. There is usually only one global instance of this class (request). If accessed during a request/response cycle, this instance always refers to the current request (even on a multithreaded server).

In other words, every time you access request in your code, Bottle does a bit of "magic" to give you a thread-local Request object. This object is not global; it is distinct from all other Request objects that may exist concurrently, e.g. in other threads. As such, it is thread safe.


Edit in response to your question about PythonDict in particular: This line makes your code thread-safe:

PythonDict={}

It's safe because you're creating a new dict every time a thread hits that line of code; and each dict you're creating is local to the thread that created it. (In somewhat more technical terms: it's on the stack.)

This is in contrast to the case where your threads were sharing a global dict; in that case, your suspicion would be right: it would not be thread-safe. But in your code the dict is local, so no thread-safety issues apply.

Hope that helps!


As far as I can see there's no reason to believe that there's a problem with threads, because your request is being served by Bottle in a single thread. Also there are no asynchronous calls in your own code that could spawn new threads that access shared variables.