使用Python和Django读取文件内容时出错

使用Python和Django读取文件内容时出错,python,django,Python,Django,我试图使用URL读取文件内容,并以html格式返回该内容作为响应,但出现以下错误: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/d

我试图使用
URL
读取文件内容,并以html格式返回该内容作为响应,但出现以下错误:

 Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/opt/lampp/htdocs/rework/Nuclear/RFI/secure/plant/views.py", line 217, in view_reactor
    pers = User.objects.get(pk=request.session['id'])
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py", line 57, in __getitem__
    return self._session[key]
KeyError: u'id'
我在下面提供我的代码:

site = 'http://127.0.0.1:8000/'
    my_list = []
    my_list.extend(['home', 'view_reactor'])
    if request.GET.get('file') is not None and request.GET.get('file') != '':
        file = request.GET.get('file')
        if file in my_list:
            full_path = site+file
            response = urllib.urlopen(full_path)
            lines = response.readlines()
            return HttpResponse(content=lines, content_type="text/html")
        else:
            return render(request, 'plant/home.html', {'count': 1})
    else:
        return render(request, 'plant/home.html', {'count': 1})


def view_reactor(request):
    """ This function for to get serch screen. """

    pers = User.objects.get(pk=request.session['id'])
    root = []
    user_name = pers.uname
    count = 1
    root.append(
        {'username': user_name,
         'count': count
         })
    return render(request, 'plant/view_reactor.html',
                  {'user': root, 'count': 1})

在这里,我传递查询字符串中的值,如下所示
http://127.0.0.1:8000/createfile/?file=view_reactor
最后,我需要
http://127.0.0.1:8000/view_reactor
html格式的页面。但是在我的代码中,我得到了这个错误。

错误是说您的
会话
字典中没有
id
键。在以下行中:

pers = User.objects.get(pk=request.session['id'])
在我看来,像这样的用户是多余的。您只需执行以下操作即可获得用户:

pers = request.user
前提是您安装了身份验证中间件

第二个选项(未测试):


共享整个堆栈trace@arjun27:我用所需代码粘贴了完整的堆栈跟踪。您的会话dict不包含id“pk=request.session['id']”我按照您的要求做了,但是它抛出了这个
AttributeError:“AnonymousUser”对象没有属性“uname”
错误。@satya这意味着用户在使用此视图之前没有经过身份验证。您应该在他登录时对他进行身份验证。@satya请查看我更新的答案
http://127.0.0.1:8000/view_reactor
在会话中有id,因为我可以直接打开它,但在这里我在查询字符串中传递相同的id,而且
内容\u type=“text/plain”
工作正常。否,它抛出了这个错误
异常值:u“auth\u user\u id”
。实际上,在登录之后,我正在会话中设置ID。
pers = User.objects.get(pk=request.session['_auth_user_id'])