|
3 | 3 | """ |
4 | 4 |
|
5 | 5 | import os |
| 6 | +import logging |
| 7 | +import sys |
6 | 8 |
|
7 | 9 | from django.core.wsgi import get_wsgi_application |
8 | 10 |
|
9 | 11 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') |
10 | 12 |
|
11 | | -application = get_wsgi_application() |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | +# Get the base WSGI application |
| 16 | +_base_application = get_wsgi_application() |
| 17 | + |
| 18 | + |
| 19 | +class BrokenPipeHandler: |
| 20 | + """ |
| 21 | + WSGI wrapper that handles BrokenPipeError gracefully. |
| 22 | + |
| 23 | + BrokenPipeError occurs when Django tries to write a response to a connection |
| 24 | + that has already been closed by the client. This is not a critical error |
| 25 | + and should be handled silently. |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self, application): |
| 29 | + self.application = application |
| 30 | + |
| 31 | + def __call__(self, environ, start_response): |
| 32 | + # Wrap start_response to catch BrokenPipeError |
| 33 | + response_sent = [False] |
| 34 | + |
| 35 | + def wrapped_start_response(status, headers, exc_info=None): |
| 36 | + try: |
| 37 | + start_response(status, headers, exc_info) |
| 38 | + response_sent[0] = True |
| 39 | + except (BrokenPipeError, OSError) as e: |
| 40 | + errno = getattr(e, 'errno', None) |
| 41 | + if errno == 32 or 'Broken pipe' in str(e) or 'BrokenPipeError' in str(type(e).__name__): |
| 42 | + logger.warning("Client disconnected during start_response") |
| 43 | + response_sent[0] = True |
| 44 | + raise |
| 45 | + raise |
| 46 | + |
| 47 | + try: |
| 48 | + # Get the response iterator |
| 49 | + response_iter = self.application(environ, wrapped_start_response) |
| 50 | + |
| 51 | + # Wrap the iterator to catch BrokenPipeError during iteration |
| 52 | + class SafeIterator: |
| 53 | + def __init__(self, iterator): |
| 54 | + # Convert to an actual iterator - Response objects are iterable |
| 55 | + # but not iterators (they have __iter__ but not __next__) |
| 56 | + self.iterator = iter(iterator) |
| 57 | + |
| 58 | + def __iter__(self): |
| 59 | + return self |
| 60 | + |
| 61 | + def __next__(self): |
| 62 | + try: |
| 63 | + return next(self.iterator) |
| 64 | + except (BrokenPipeError, OSError) as e: |
| 65 | + errno = getattr(e, 'errno', None) |
| 66 | + if errno == 32 or 'Broken pipe' in str(e) or 'BrokenPipeError' in str(type(e).__name__): |
| 67 | + logger.warning("Client disconnected during response iteration") |
| 68 | + raise StopIteration |
| 69 | + raise |
| 70 | + |
| 71 | + def close(self): |
| 72 | + if hasattr(self.iterator, 'close'): |
| 73 | + try: |
| 74 | + self.iterator.close() |
| 75 | + except (BrokenPipeError, OSError) as e: |
| 76 | + errno = getattr(e, 'errno', None) |
| 77 | + if errno == 32 or 'Broken pipe' in str(e) or 'BrokenPipeError' in str(type(e).__name__): |
| 78 | + logger.warning("Client disconnected during response close") |
| 79 | + return |
| 80 | + raise |
| 81 | + |
| 82 | + return SafeIterator(response_iter) |
| 83 | + |
| 84 | + except (BrokenPipeError, OSError) as e: |
| 85 | + # Check if it's a broken pipe error (client disconnected) |
| 86 | + errno = getattr(e, 'errno', None) |
| 87 | + if errno == 32 or 'Broken pipe' in str(e) or 'BrokenPipeError' in str(type(e).__name__): |
| 88 | + # Client disconnected - log as warning but don't fail |
| 89 | + logger.warning(f"Client disconnected during response (operation may have succeeded)") |
| 90 | + # Return an empty response |
| 91 | + if not response_sent[0]: |
| 92 | + try: |
| 93 | + wrapped_start_response('200 OK', []) |
| 94 | + except: |
| 95 | + pass |
| 96 | + return [] |
| 97 | + # Re-raise other OSErrors |
| 98 | + raise |
| 99 | + |
| 100 | + |
| 101 | +# Wrap the application to handle BrokenPipeError |
| 102 | +application = BrokenPipeHandler(_base_application) |
0 commit comments