我正在尝试使用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
页面的响应。但在我的代码中,我收到了这个错误。
答案 0 :(得分:1)
错误是您的id
字典中没有session
个密钥。在以下行中:
pers = User.objects.get(pk=request.session['id'])
对我来说,让这样的用户看起来多余。您应该能够通过这样做来获得用户:
pers = request.user
前提是您已安装auth中间件。
第二个选项(虽未测试):
pers = User.objects.get(pk=request.session['_auth_user_id'])