简体   繁体   English

用于text / xsl的Django Content-Type

[英]Django Content-Type for text/xsl

I have been trying to set the content type for an xsl file. 我一直在尝试为xsl文件设置内容类型。 This is what I have done so far 这是我到目前为止所做的

def xsl_content_type():

    filename = static('sitemap.xsl')
    response = HttpResponse(filename)
    response['Content-Type'] = "text/xsl"
    response['Content-Length'] = len(filename)
    return response

This returns 这返回

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: *

Even thought I did setup the Content-Type as text/xsl , all I get is application/octet-stream . 即使以为我确实将Content-Type设置为text/xsl ,我得到的只是application/octet-stream I have also tried doing response = HttpResponse(filename, content_type="text/xsl") , but the content type is the same. 我也尝试过做response = HttpResponse(filename, content_type="text/xsl") ,但是内容类型是相同的。

What am I missing here? 我在这里想念什么?

There could be a better way, but the following helped me 可能有更好的方法,但是以下方法对我有帮助

urls.py urls.py

add url(r'^sitemap\\.xsl', xsl_content_type, name='sitemap_xsl') to urlpatterns url(r'^sitemap\\.xsl', xsl_content_type, name='sitemap_xsl')urlpatterns

views.py views.py

Add the following code: 添加以下代码:

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")

Note: The DYNO is a Heroku environment variable, you can add your own environment variable (if needed) when using in production. 注意: DYNO是Heroku环境变量,在生产中使用时可以添加自己的环境变量(如果需要)。

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

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