如何修改响应.内容在Django中间件中调用方法

2024-10-02 12:31:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过在中间件中处理xml响应中的所有空行,如本例所示:https://code.djangoproject.com/wiki/StripWhitespaceMiddleware
现在的问题是,在Django 2.1中,自dajngo1.10以来,该代码不再是最新的,中间件的工作方式发生了很大的变化。
现在我看到响应.内容类型为bytes,因此无法直接使用regex进行编辑。
在django1.10+中正确的方法是什么?在


Tags: 中间件django代码httpscom类型内容方式
1条回答
网友
1楼 · 发布于 2024-10-02 12:31:32

正如您所说,response.content是一个bytes,因此regex中的所有参数都必须是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    

documentation

Both patterns and strings to be searched can be Unicode strings (str) as well as 8-bit strings (bytes). 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; similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string.

相关问题 更多 >

    热门问题