Created
April 15, 2014 08:45
-
-
Save wichert/10714681 to your computer and use it in GitHub Desktop.
Example of integration rq with transactions
This file contains 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
def enqueue(request, queue, func, *a, **kw): | |
"""Queue a function call. | |
:param request: Pyramid request object | |
:param queue: name of the rq queue to use | |
:param func: function or instance method to call | |
:return: rq job instance | |
>>> enqueue(request, 'email', myfunc, arg1, arg2) | |
""" | |
# Get the right rq queue. This is highly application-specific and will likely | |
# differ for everyone. | |
queue = request.registry.settings['_rq_queues'][queue] | |
job = Job.create( | |
func, a, kw, connection=queue.connection, status=Status.QUEUED) | |
# Pyramid-specific trick: add the authenticated userid to the job. This is | |
# useful to manage authorisation when a user later wants to poll for job | |
# status/result. | |
job.meta['creator'] = authenticated_userid(request) | |
# Setup an after-commit hook for the current transaction. | |
tx = transaction.get() | |
def hook(status): | |
if status: | |
# Only queue if the transaction was succesfull. | |
queue.enqueue_job(job) | |
tx.addAfterCommitHook(hook) | |
return job |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment