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

时间:2014-12-12 08:40:35

标签: python django

好吧,我有中间件类,需要确定呈现页面的内容类型 如果它是'txt / html',那么就做一些动作。我刚刚开始看到我在页面上有哪些内容类型,这是我遇到的第一个问题:

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']

执行此操作时,我收到的关于页面元素的内容类型的消息很少,例如text/htmlapplication/javascript以及 大量错误,例如key error: content-type,之后是broken pipe

所以我假设并非页面的所有元素都有这样的标题Content-Type,我的问题如下:

是否有一些通用的Content-Type表示“该页面是text / html”或页面上有很多内容类型?

此外,如果这是一种确定内容类型的页面的正确方法:

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

2 个答案:

答案 0 :(得分:1)

我不知道你为什么会有这些例外。根据{{​​3}} HttpResponse总是有Content-Type。默认类型设置在django source code

您可以找到的所有mime类型的列表settings。但我很确定' text / html'是你需要的。

您还可以先检查响应类型,然后使用.get()函数检查内容类型,以避免不必要的异常:

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

一些测试:

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

答案 1 :(得分:-1)

' text / html的'或者' xml'是文本文件。 "内容类型"是文件中的文字。

<?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