Simulating HTTP responses in Django.

One of the most important aspects of your web application's client side code is how it handles errors and slow connections. In the case of an error, some reasonable error message should be displayed and in the case of a slow connection, the user shouldn't be left staring at the web app wondering why did it freeze and you should at least display a spinning wheel or some other "in progress" indicator.

To solve that problem in Django, you can write a simple Django application that simulates errors and slow connections. The way it works is by installing a middleware component that catches HTTP requests and returns error codes, or sleeps for some time before returning.

I'll illustrate how to implement a very simple version of that idea. Let's say that you'll have a handler sitting at "/http_simulate", which when accessed will switch the server from error mode to healthy mode and then back. The second thing you need is a middleware that knows what mode the server is in and depending on that, fiddles with the HTTP request and produces an error HTTP response.

Here's how a very simple middleware class would look like:

Notice how that middleware class ignores requests which go to the view that switches to error mode. You want to be able to switch back to normal mode once you switch to error mode.

The second part you need is a view that switches the IN_ERROR_MODE variable.

After you have this code, you can just create a simple Django application and install that middleware in your settings.py file. Be careful to not have that turned on in your production environment.

There are also many ways in which this can be extended:

  • Support for different error codes.
  • Support for slow connections by sleeping before sending the HTTP response.
  • Setting error mode for only specific urls, not for every request sent to the server.

social