Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly handle an aborted HTTP request in Django

Tags:

django

Whenever a lengthy HTTP requests is aborted by the client (e.g. Browser is closed) Django views seem to raise a IOError exception.

What's the proper way to detect such an aborted request if I just want to ignore them? Just catching IOError seems too wide.. might accidentally ignore other IO problems.

like image 693
Assaf Lavie Avatar asked Nov 22 '25 14:11

Assaf Lavie


1 Answers

In django 1.3 and up, you can use a logging filter class to suppress the exceptions which you aren't interested in. Here's the logging filter class I'm using to narrowly suppress IOError exceptions raised from _get_raw_post_data():

import sys, traceback
class _SuppressUnreadablePost(object):
    def filter(self, record):
        _, exception, tb = sys.exc_info()
        if isinstance(exception, IOError):
            for _, _, function, _ in traceback.extract_tb(tb):
                if function == '_get_raw_post_data':
                    return False
        return True

In Django 1.4, you will be able to do away with most of the complexity and suppress the new exception class UnreadablePostError. (See this patch).

like image 70
dlowe Avatar answered Nov 25 '25 11:11

dlowe