In CherryPy, each request runs in a thread, and that thread has access to a session object via cherrypy.session. If, from that request thread, you launch another thread, thereby allowing the request to return, you no longer have access to that session object. Is there any way around this?
I have a function that runs when the user loads a specific page. Under certain circumstances, this function could take some time (say 10 seconds or so) to run. The results of this function aren't used directly in page rendering, rather they are stored in the users session object for later (instant) retrieval when the user clicks a button. Rather than make the user wait for the data to be compiled, I would like to offload this function to a background thread and let the main thread return the page to the user, but when I do that I no longer have access to the users session object to store the result. How can I work around this? Thanks.
In my specific situation, I am using a custom class for my session (a PostgreSQL session class), but I would think the same procedure would apply regardless. When the initial request comes in, I pull the session_id
from the cherrypy.request.cookie
object, and pass it to the function that I run in the child thread.
Then, in that function, when I need to access the session object, I instantiate a new session object myself using the session_id
, and after setting the desired value call save()
on the instance. Works perfectly for me!