Created
March 3, 2017 23:39
-
-
Save mmerickel/d563758185c84ae66f421df50eb4bcf0 to your computer and use it in GitHub Desktop.
update shared data in the background
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import time | |
import transaction | |
from .models import get_tm_session | |
def worker(dbsession_factory, registry): | |
while True: | |
tm = transaction.TransactionManager(explicit=True) | |
with tm: | |
dbsession = get_tm_session(dbsession_factory, tm) | |
some_objs = dbsession.query(...) | |
results = serialize(some_objs) | |
with registry['background_payload_lock']: | |
registry['background_payload'] = results | |
time.sleep(60) | |
def view(request): | |
with request.registry['background_payload_lock']: | |
results = request.registry['background_payload'] | |
some_objs = deserialize(results) | |
def main(global_config, **settings): | |
config = Configurator(settings=settings) | |
config.include('.models') | |
# prepare the registry to handle background work | |
config.registry['background_payload_lock'] = threading.Lock() | |
config.registry['background_payload'] = {} | |
dbsession_factory = config.registry['dbsession_factory'] | |
t = threading.Thread(target=worker, args=(dbsession_factory, config.registry)) | |
t.daemon = True | |
t.start() | |
return config.make_wsgi_app() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment