librelist archives

« back to archive

WSGI Initialization and Cleanup Code?

WSGI Initialization and Cleanup Code?

From:
Andy Sayler
Date:
2014-02-10 @ 06:56
Hello,

I'm new to the list, so apologies if this has come up before (although
a cursory search of the list archives and docs didn't provide me with
a clear answer).

Does flask have a method for supporting run-once initialization and
cleanup code when running under WSGI with multiple WSGI threads? I.e.
Is there a way to run a block of code when Apache (or your WSGI server
of choice) starts (or starts the WSGI application) and again when
Apache stops (or stops the WSGI application)? The code must only be
run once regardless of the number of WSGI handler threads, requests,
etc and must always be run before accepting any requests on startup
and after processing the last request on shutdown.

Without getting too lost in the underlying details, I ask because I
have a couple of on-disk databases that I need to provide atomic
access to across parallel requests: E.g. I have two DBs, DB1 that maps
UUIDs to version numbers and DB2 that maps the same UUIDs to values.
Two requests arrive in parallel: R1 updating an object and R2 reading
the same object. I need to guarantee that R1 can update both DB1
(object version) and DB2 (object value) atomically while ensuring that
R2 either gets the pre-R1 update values from DB1 and DB2 or the
post-R1 update values from DB1 and DB2, but not an interleaved
combination of the values.

I have a system for accomplishing this using Posix named semaphores
(to support synchronization across multiple wsgi processes as
described at 
http://stackoverflow.com/questions/5710836/how-can-i-control-access-to-a-shared-resource-when-using-mod-wsgi)
and the posix_ipc python package
(http://semanchuk.com/philip/posix_ipc/), but I need the ability to
initialize and cleanup these semaphores properly. Hence the need for
init and cleanup code support in flask.

Thoughts?

Thanks,
Andy Sayler
www.andysayler.com