0

在我的 views.py 中,以下示例有效:

def get_stats_file (request):
    ...
    stats_file = settings.PROJECT_ROOT + "my.stats.txt"
    return HttpResponse (stats_file)

下面给出如下所示的错误。唯一的区别是,我不是从函数内部创建 stats_file 字符串,而是在另一个函数中创建它。

def get_absolute_path (filename):
    return settings.PROJECT_ROOT + filename

def get_stats_file (request):
    stats_file = get_absolute_path("my.stats.txt")
    return HttpResponse (stats_file)

错误:

Request Method: GET
Request URL: http://a.b.c.d:8000/XXX/XXX/XXX/XXX/XXX/

Django Version: 1.4.3
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'visualizer')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')

Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/amsaha/XXX/XXX/XXX/XXX/XXX/views.py" in get_port_info
  39.     stats_file = get_absolute_path("my.stats.txt")
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  90.         add_never_cache_headers(response)
File "/usr/local/lib/python2.7/dist-packages/django/utils/cache.py" in add_never_cache_headers
  129.     patch_response_headers(response, cache_timeout=-1)
File "/usr/local/lib/python2.7/dist-packages/django/utils/cache.py" in patch_response_headers
  119.     if not response.has_header('Last-Modified'):

Exception Type: AttributeError at /XXX/XXX/XXX/XXX/XXX
Exception Value: 'str' object has no attribute 'has_header'

我一定是在做一些非常简单的错误:-)

4

1 回答 1

0

你确定这是所有相关的代码吗?

首先,HttpResponse 不提供将给定文件名添加到响应中的功能。您所说的是“给我一个与文件名相同的正文,而不是该文件名的文件内容”。如果你想要实际的内容,你应该做 HttpResponse(open(filename).read(), content_type="mimetype of the file")

其次,堆栈跟踪似乎暗示您正在从视图返回一个字符串,而不是一个 HttpResponse 实例,这让我相信您没有共享足够的代码让我们看到发生了什么。

于 2013-11-08T07:27:52.323 回答