django - HttpRequest 对象没有属性 'session'

标签 django session httprequest django-unittest

我似乎无法让 session 工作。 Django 提示 HttpRequest 对象没有名为“ session ”的属性。在文档中,它明确指出,如果您启用了中间件,并且已安装应用程序中的 django.contrib.sessions,那么您就可以开始了。我使用单元测试收到此错误。

在我的 views.py 中:

def home_page(request):
    response = render(request, 'home.html', {'message_text' : request.session.get('message_text', ''),
'ip_address'    :   request.session.get('ip_address', ''),
'port_number'   :   request.session.get('port_number', ''),
'command_text'  :   request.session.get('command_text', ''),})

    request.session['message_text'] = ''

    return response

我试图获得的 session 值是我试图在 views.py 中其他地方的表单发布方法中设置的值。

它还指出,这些在新项目中默认启用。所以我创建了一个全新的 django 项目并在控制台中检查了 session 属性。这正是我所做的:
(django1.5)Python $ django-admin.py startproject testing
(django1.5)Python $ cd testing/
(django1.5)testing $ python manage.py shell
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.http import HttpRequest
>>> r = HttpRequest()
>>> r.session
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'HttpRequest' object has no attribute 'session'
>>>

我错过了什么??

更新:这仅在使用单元测试进行测试时发生。这是导致异常的测试:
def test_home_page_returns_correct_html(self):
        request = HttpRequest()
        response = home_page(request)
        expected_html = render_to_string('home.html')
        self.assertEqual(response.content, expected_html)

最佳答案

将以下内容添加到测试文件的顶部:

from django.conf import settings
from django.utils.importlib import import_module

那么这应该工作:
def test_home_page_returns_correct_html(self):
    request = HttpRequest()
    engine = import_module(settings.SESSION_ENGINE)
    session_key = None
    request.session = engine.SessionStore(session_key)
    response = home_page(request)
    expected_html = render_to_string('home.html')
    self.assertEqual(response.content, expected_html)

关于django - HttpRequest 对象没有属性 'session',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16865947/

相关文章:

python - 多项选择未保存在数据库中

django - HTML5 离线存储 web 框架

java - 如何在单元测试中处理 session 变量

bash - 使用 HTTP 请求在 privnote.com 中创建注释

ruby - 从 Sinatra 发送 DELETE 请求

python - 找不到 django 静态目录

ajax - 使用 Dajax 调用 Django View

php - Windows/Temp 目录中充满了阻塞服务器的 Php Session 文件

java - 如何在 Spring WebSocketStompClient 中获取 Session Id?

android - Webview 仅在某些页面上显示原始 HTML 文本