![](/img/trans.png)
[英]Django: Multiple Content-Type: text/html appears on html page
[英]Django Content-Type for text/xsl
我一直在尝试为xsl
文件设置内容类型。 这是我到目前为止所做的
def xsl_content_type():
filename = static('sitemap.xsl')
response = HttpResponse(filename)
response['Content-Type'] = "text/xsl"
response['Content-Length'] = len(filename)
return response
这返回
HTTP/1.0 200 OK
Date: Wed, 13 Sep 2017 05:04:46 GMT
Server: WSGIServer/0.2 CPython/3.6.1
Last-Modified: Tue, 13 Jun 2017 03:54:17 GMT
Content-Length: 7134
Content-Type: application/octet-stream
Cache-Control: max-age=0, public
Access-Control-Allow-Origin: *
即使以为我确实将Content-Type
设置为text/xsl
,我得到的只是application/octet-stream
。 我也尝试过做response = HttpResponse(filename, content_type="text/xsl")
,但是内容类型是相同的。
我在这里想念什么?
可能有更好的方法,但是以下方法对我有帮助
urls.py
将url(r'^sitemap\\.xsl', xsl_content_type, name='sitemap_xsl')
到urlpatterns
views.py
添加以下代码:
def xsl_content_type(request):
"""
Converts the MIME type of `sitemap.xsl`.
Returns
-------
HttpResponse: HttpResponse
Returns `sitemap.xsl`.
"""
if 'DYNO' in os.environ:
url = os.path.join(settings.STATIC_URL, 'sitemap.xsl')
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers = {'User-Agent': user_agent, }
request = urllib.request.Request(url, None, headers)
response = urllib.request.urlopen(request)
data = response.read().decode('UTF-8')
else:
data = open(os.path.join(settings.STATIC_ROOT, 'sitemap.xsl')).read()
return HttpResponse(data, content_type="text/xsl")
注意: DYNO
是Heroku环境变量,在生产中使用时可以添加自己的环境变量(如果需要)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.