简体   繁体   English

确定中间件类Django中页面的内容类型

[英]Determine content-type of page in middleware class Django

Well, I have middleware class which is required to determine content-type of rendered page and if it is 'txt/html', then do some action. 好吧,我有一个中间件类,它需要确定呈现页面的内容类型,如果它是'txt / html',则执行一些操作。 I've started just from seeing what content-types do I have on page and here is first problem I faced: 我只是从查看页面上有哪些内容类型开始的,这是我面临的第一个问题:

class StatsMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
              response = view_func(request, *view_args, **view_kwargs)
              print response['Content-Type']

Executing this, I get few messages about content-types of page elements, like text/html , application/javascript and also tons of errors like key error: content-type and after that - broken pipe 执行此操作后,我收到一些有关页面元素的内容类型的消息,例如text/htmlapplication/javascript以及大量错误,例如key error: content-type及之后- broken pipe

So I assume that not all elements of page have such header Content-Type and my question is following: 因此,我假设并非页面的所有元素都具有此类标题Content-Type而我的问题如下:

Is there some general Content-Type that says 'That page is text/html' or there are a lot of content-types on page ? 是否有一些通用的Content-Type表示“该页面是text / html”,或者页面上有很多Content-Type?

And also if this is a proper way to deterimne content-type of page like this: 而且,如果这是确定像这样的页面内容类型的正确方法,则:

if response['Content-Type'] == 'text/html':
     pass

I don't know why do you have those exceptions. 我不知道你为什么有这些例外。 According to django source code HttpResponse always have Content-Type. 根据Django源代码, HttpResponse始终具有Content-Type。 Default type sets in settings 设置中的默认类型设置

List of all mime-types you can find here . 您可以在此处找到所有mime类型的列表。 But I'm pretty sure that 'text/html' is what you need. 但是我很确定'text / html'是您所需要的。

You can also check type of response at first, and then check for content-type using .get() function to avoid unnecessary exceptions: 您还可以首先检查响应的类型,然后使用.get()函数检查内容类型,以避免不必要的异常:

if isinstance(response, HttpResponse):
  if response.get('Content-Type').count('text/html'):
     response=big_magic(response)
return response

Some tests: 一些测试:

Python 3.4.2 (default, Oct  8 2014, 13:14:40) 
[GCC 4.9.1] on linux
Django 1.7
>>> from django.http import response
>>> r = response.HttpResponse('some content')
>>> r['Content-Type']
'text/html; charset=utf-8'
>>> response.HttpResponseRedirect('/some/url')['Content-Type']
>>> response.HttpResponseRedirect('/some/url').get('Content-Type').count('text/html')
1

'text/html' or 'xml' is text files. “ text / html”或“ xml”是文本文件。 "Content-Type" is text in file. “内容类型”是文件中的文本。

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to> Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

if "<?xml" in page then - xml else - html

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

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