我有下面的视图,它要么获取一个URL,要么获取一个上传的文本文件,创建一个wordcloud,最后将生成的图像显示给用户。你知道吗
def create(request):
"""
Displays the generated WordCloud from the
given URI or uploaded file
"""
response = HttpResponse(content_type="image/png")
# in order to avoid KeyError
myfile = request.FILES.get('myfile', None)
if request.POST['uri'] == '' and myfile is None:
return render(request, 'nube/index.html', {
'error_message': NOTHING_TO_PROCESS
})
try:
if myfile:
cloud = WordCloud(myfile, type="upload")
else:
cloud = WordCloud(request.POST['uri'], type="internet")
except (MissingSchema):
return render(request, 'nube/index.html', {
'error_message': URI_COULD_NOT_BE_PROCESSED
})
else:
# img is a PIL.Image instance
img = cloud.get_word_cloud_as_image()
img.save(response, 'PNG')
return response
图像显示没有问题;POST请求处理正确,从日志中可以看出:
[16/Jan/2018 22:53:25] "POST /nube/create HTTP/1.1" 200 216961
但是,即使服务器没有崩溃,我也注意到每次紧接着发生以下情况时都会引发异常:
Internal Server Error: /nube/create
Traceback (most recent call last):
File "C:\repos\phuyu\venv\lib\site-packages\django\utils\datastructures.py", line 77, in __getitem__
list_ = super().__getitem__(key)
KeyError: 'uri'
调试完代码后,我注意到我的create
视图再次被调用,但这次作为GET请求调用,当然,参数uri
和myfile
这次不存在,因此引发了异常。你知道吗
为了确保这一点,我将create
更改为基于类的视图,并且只定义了它的post
方法。正如我所怀疑的,在成功发布后,我在日志中看到了以下一行:
Method Not Allowed (GET): /nube/create
[16/Jan/2018 22:44:41] "GET /nube/create HTTP/1.1" 405 0
正确的处理方法是什么?我刚到Django。你知道吗
正如@usman maqbool所建议的,问题实际上是在我的WordCloud clode中,特别是在
get_word_cloud_as_image()
,一个尾随的分号中:删除它之后,就不再有偷偷摸摸的GET请求了。我不知道为什么会有这种效果。如果有人能澄清一下,我将不胜感激。你知道吗
相关问题 更多 >
编程相关推荐