繁体   English   中英

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

[英]Determine content-type of page in middleware class 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”,或者页面上有很多Content-Type?

而且,如果这是确定像这样的页面内容类型的正确方法,则:

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

我不知道你为什么有这些例外。 根据Django源代码, HttpResponse始终具有Content-Type。 设置中的默认类型设置

您可以在此处找到所有mime类型的列表。 但是我很确定'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

“ 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

暂无
暂无

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

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