Search code examples
pyramid

How to prevent two users execute a function inside a Pyramid view


I have a Pyramid view connected to a route like /my/view

Because the architecture of Pyramid two requests can access the same view at the same time. Inside my view, I have a function that only one user should access at a time, meaning: If user A is processing that function and user B calls the view then user B does not enter into that function until A finishes.

I tried with:

lock.acquire()
try:
    my_function()
finally:
    lock.release()

But since Pyramid starts a new thread with each request it does not work.

Any idea of how can I control this?


Solution

  • Your lock should work, assuming the lock is defined in a place that is shared between calls to the view (module variable, registry variable, etc). It's worth noting that Pyramid itself doesn't start new threads. That's done by your WSGI server and the details of each server matter for answering your question.

    If you're using waitress, then requests are handled by threads and thus in the shared memory space you can share a lock between requests. In other scenarios a separate process is used for each request, at which point a thread-level lock will have no effect. So it depends on your deployment where exactly is the best place to define the lock. For example, to share a lock across processes, a good spot is in redis or your database.