簡體   English   中英

用於text / xsl的Django Content-Type

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM