| 1 |
# -*- coding: utf-8 -*- |
| 2 |
import logging |
| 3 |
import random |
| 4 |
|
| 5 |
from django.utils.crypto import get_random_string |
| 6 |
from django.utils.deprecation import MiddlewareMixin |
| 7 |
from django.utils.encoding import force_str |
| 8 |
|
| 9 |
|
| 10 |
log = logging.getLogger(__name__) |
| 11 |
|
| 12 |
|
| 13 |
class RandomCommentMiddleware(MiddlewareMixin): |
| 14 |
|
| 15 |
def process_response(self, request, response): |
| 16 |
if not getattr(response, 'streaming', False) \ |
| 17 |
and response.get('Content-Type', '').startswith('text/html') \ |
| 18 |
and response.content \ |
| 19 |
and isinstance(response.content, (bytes, str)) \ |
| 20 |
and not getattr(response, '_random_comment_exempt', False) \ |
| 21 |
and not getattr(response, '_random_comment_applied', False): |
| 22 |
comment = '<!-- {0} -->'.format( |
| 23 |
get_random_string(random.choice(range(12, 25)))) |
| 24 |
response.content = '{0}{1}'.format( |
| 25 |
force_str(response.content), comment) |
| 26 |
response._random_comment_applied = True |
| 27 |
if response.has_header('Content-Length'): |
| 28 |
response['Content-Length'] = str(len(response.content)) |
| 29 |
return response |