简体   繁体   中英

Django Content-Type for text/xsl

I have been trying to set the content type for an xsl file. 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 . I have also tried doing response = HttpResponse(filename, content_type="text/xsl") , but the content type is the same.

What am I missing here?

There could be a better way, but the following helped me

urls.py

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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