带函数返回的字符串的HttpResponse给'str'对象没有属性'has_header'

时间:2013-11-08 05:01:25

标签: python django django-views

从我的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)

ERROR:

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'

我必须做一些非常简单的错误: - )

1 个答案:

答案 0 :(得分:0)

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

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

其次,stacktrace似乎意味着你从视图中返回一个字符串而不是一个HttpResponse实例,这让我相信你没有分享足够的代码让我们看到发生了什么事。