Django在Apache下的内容类型问题,静态HTML + CSS文件?

时间:2012-09-19 21:55:17

标签: django apache nginx content-type x-sendfile

我正在尝试在Django下提供静态文件(HTML + CSS)。 (稍后,我会用密码保护他们)。但是,我得到了错误的内容类型。下载HTML文件,而不是显示。

我的网络服务器是Apache,我在Webfaction下运行它。我正在查看Chromium 18下的网站。

我正在尝试一个天真的FileWrapper(从Django发送文件)方法,我使用mimetype来确定类型,以及x_modsendfile,我让网络服务器决定。

下载HTML文件,但不显示。

当我通过我的Apache网络服务器而不是Django服务时,内容标题应该是的内容:

HTTP/1.1 200 OK => 
Server => nginx
Date => Wed, 19 Sep 2012 21:51:35 GMT
Content-Type => text/html
Content-Length => 9362
Connection => close
Vary => Accept-Encoding
Last-Modified => Wed, 19 Sep 2012 05:53:00 GMT
ETag => "e3a0c43-2492-4ca079e8fea23"
Accept-Ranges => bytes

观察服务器声称是nginx。 Webfaction说,对于静态服务,它设置了Apache,实际上我一直在为Django配置Apache服务器。但是回复说Nginx(!)

以下是来自天真的FileWrapper实现的响应,其中我使用mimetypes选择Content-Type:

HTTP/1.1 200 OK => 
Server => nginx
Date => Wed, 19 Sep 2012 21:53:28 GMT
Content-Type => ('text/html', none)
Content-Length => 9362
Connection => close

内容类型是TUPLE。

以下是mod_xsendfile实现的响应,其中我没有选择Content-Type:

HTTP/1.1 200 OK => 
Server => nginx
Date => Wed, 19 Sep 2012 21:52:40 GMT
Content-Type => text/plain
Content-Length => 9362
Connection => close
Vary => Accept-Encoding
Last-Modified => Wed, 19 Sep 2012 05:53:00 GMT
ETag => "e3a0c43-2492-4ca079e8fea23"

这是我的代码:

def _serve_file_xsendfile(abs_filename):
    response = django.http.HttpResponse() # 200 OK
    del response['content-type'] # We'll let the web server guess this.
    response['X-Sendfile'] = abs_filename
    return response

def _serve_file_filewrapper(abs_filename):
    p_filename = abs_filename
    if not os.path.exists(p_filename):
        raise Exception('File %s does not exist!')

    try:
        _content_type = mimetypes.guess_type(p_filename)
    except:
        _content_type = 'application/octet-stream'

    print p_filename, _content_type

    wrapper = FileWrapper(file(p_filename))
    response = HttpResponse(wrapper, content_type=_content_type)
    response['Content-Length'] = os.path.getsize(p_filename)
    response['Content-Type'] = _content_type
    return response

def _serve_file(filename):
    abs_filename = _get_absolute_filename(filename)
    return _serve_file_filewrapper(abs_filename)

def public_files(request, filename):
    return _serve_file(filename)

如何为FileWrapper或mod_xsendfile方法获取正确的Content-Type?

1 个答案:

答案 0 :(得分:0)

_content_type = mimetypes.guess_type(p_filename)

应该是

_content_type, encoding = mimetypes.guess_type(p_filename)