简体   繁体   English

如何修改 Django 中间件 __call__ 方法中的 response.content

[英]How can I modify the response.content in a Django Middleware __call__ method

I'm trying to remove all blank lines in xml response by processing it in a middleware as suggested in this example: https://code.djangoproject.com/wiki/StripWhitespaceMiddleware我试图通过在中间件中处理它来删除 xml 响应中的所有空行,如本示例中所示: https : //code.djangoproject.com/wiki/StripWhitespaceMiddleware
Now the problem is that in Django 2.1 that code is no more current since Dajngo 1.10 the way the Middleware works changed quite a bit.现在的问题是,在 Django 2.1 中,自 Dajngo 1.10 以来,该代码不再是最新的,中间件的工作方式发生了很大变化。
Now I see that the response.content is of type bytes and so no straightforward editable with regex.现在我看到 response.content 是字节类型,因此无法使用正则表达式直接编辑。
What is the correct way to do this in Django 1.10+?在 Django 1.10+ 中执行此操作的正确方法是什么?

As your said, response.content is a bytes so all arguments in the regex have to by of type byte , including the replacement string.正如您所说, response.content是一个bytes因此正则表达式中的所有参数都必须为byte类型,包括替换字符串。

    def __init__(self):
        self.whitespace = re.compile(b'^\s*\n', re.MULTILINE)
        #self.whitespace_lead = re.compile(b'^\s+', re.MULTILINE)
        #self.whitespace_trail = re.compile(b'\s+$', re.MULTILINE)


    def process_response(self, request, response):
        if "text" in response['Content-Type']:
        #Use next line instead to avoid failure on cached / HTTP 304 NOT MODIFIED responses without Content-Type
        #if response.status_code == 200 and "text" in response['Content-Type']:
            if hasattr(self, 'whitespace_lead'):
                response.content = self.whitespace_lead.sub(b'', response.content)
            if hasattr(self, 'whitespace_trail'):
                response.content = self.whitespace_trail.sub(b'\n', response.content)
            if hasattr(self, 'whitespace'):
                response.content = self.whitespace.sub(b'', response.content)
            return response
        else:
            return response    

From the documentation :文档

Both patterns and strings to be searched can be Unicode strings (str) as well as 8-bit strings (bytes).要搜索的模式和字符串都可以是 Unicode 字符串(str)以及 8 位字符串(字节)。 However, Unicode strings and 8-bit strings cannot be mixed : that is, you cannot match a Unicode string with a byte pattern or vice-versa;但是,Unicode 字符串和 8 位字符串不能混合使用:也就是说,不能将 Unicode 字符串与字节模式匹配,反之亦然; similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string.类似地,当要求替换时,替换字符串必须与模式和搜索字符串的类型相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM