Post function on play()

26 March 2014

Introduction

I've been trying to write documentation for Burst for quite a long time now without any success. Probably because I prefer spending the spare time I have on implementing new features. A colleague of mine suggested that writing real-world use case could be a good start, so here we are.

This post focus on the post_func argument of the play method of the Request class. This method is used to spawn an instance of your editor with two windows: one for the request and one for the response. Whenever the request file is modified and saved, the request is sent to the server and the response file updated accordingly. This is very useful for interactive testing of web applications. Few arguments exists for this method, including the post_func callback.

The post_func callback is used to perform some action on the response before displaying it back to the user. As one would expect, it takes a Response object as argument and should return a Response object.

Use case

Now, imagine a form on a web page that behaves in the following manner: when the form is submitted (POST), the fields are updated (with some limited validation) and the page rendered with the new values. But when the same form is requested again (GET), the value rendered differs from what has been previously rendered. In that case, using the default play method is not relevant as you have limited interest in the values rendered directly after validation.

The post_func parameters can be used for that purpose. Instead of rendering the returned page, we will request the page again and return that page instead. We start with our two requests:

>>> r1
<GET www.example.org /form>
>>> r2
<POST www.example.org /form>

Now let's add our callback. This will simply ignore the Response received, call the first Request (GET) and return its Response.

>>> def ignore_and_refresh(r):
...   r1()
...   return r1.response

Finally, let's use that callback in our play call:

>>> r2.play(post_func=ignore_and_refresh)

Extra

You may want a different behaviour than what we have just seen. For instance if the POST request returns a 500 error, you want to know about it. In this case, modifying the callback with a conditional statement will do the trick. As usual with Burst, you are in control of what you want to test.