Chung Wu
Chung Wu

Reputation: 2417

In Pylons, how do I perform actions after writing the response?

In a pylons controller, I would like to first return the response to the request (so that the user gets a response ASAP), and then perform some additional operations (say, updating view counts, etc.) that didn't need to happen to generate the response. What's the best-practice for doing things like this?

Thanks!

Upvotes: 3

Views: 272

Answers (2)

ddotsenko
ddotsenko

Reputation: 4996

On most wsgi-based servers (like the standard wsgiref, nwsgi etc) there is a way to send some portion of a body out work a little more and send some more. I guess the "send some more" is optional.

Use yield instead of return. WSGI example (not sure if it translates well into Pylons):

def application(environ, start_response):
    start_response('200 OK', [('Content-type','text/plain')])
    yield 'body starts. You should see this in browser already'
    # do something
    yield 'some more of body'

Once the request handler runs out of code to run, it closes the connection.

Now, this is sure to work on standard wsgi servers I tried. I would like to hear if this works on Pylons.

Upvotes: 1

Antoine Leclair
Antoine Leclair

Reputation: 18050

I did not have the chance to try Python threads yet, but you could do something like:

def controller_method(self):
    # controller logic here
    html = render('/template.mako')
    # start a thread here
    return html

By starting the thread after all the logic, but just before returning, you should avoid conflicts between the threads.

You might also have a look at RabbitMQ or other message queuing software. You could offload your main web application by sending the jobs in a queue.

Upvotes: 0

Related Questions