我一直在尝试设置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")
,但内容类型相同。
我在这里缺少什么?
答案 0 :(得分:0)
可能有更好的方法,但以下帮助我
<强> 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环境变量,您可以在生产中使用时添加自己的环境变量(如果需要)。