繁体   English   中英

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

[英]Getting error while reading the file content using Python and 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/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 ,最后我需要以html格式返回http://127.0.0.1:8000/view_reactor页面。 但是在我的代码中,我得到了这个错误。

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

pers = User.objects.get(pk=request.session['id'])

对我来说,获得这样的用户似乎是多余的。 您只需通过执行以下操作就可以吸引用户:

pers = request.user

前提是您已安装身份验证中间件。

第二种选择(虽然未测试):

pers = User.objects.get(pk=request.session['_auth_user_id'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM