为什么Django会在POST后触发GET?

时间:2018-01-17 04:01:42

标签: python django pillow

我有以下视图,该视图采用URL或上传的文本文件,创建Word Cloud,最后将生成的图像显示给用户。

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请求,当然,参数urimyfile没有'这次存在,从而引发例外。

为了确保,我将create更改为基于类的视图,并仅定义了其post方法。如所怀疑的,现在我在POST成功后的日志中得到以下行:

Method Not Allowed (GET): /nube/create
[16/Jan/2018 22:44:41] "GET /nube/create HTTP/1.1" 405 0

处理此问题的正确方法是什么?我是Django的新手。

1 个答案:

答案 0 :(得分:0)

正如@ usman-maqbool所说,问题实际上是在我的WordCloud clode中,特别是在get_word_cloud_as_image()中,一个尾随的分号:

  def get_word_cloud_as_image(self):
        return self.img;

删除后,不再有偷偷摸摸的GET请求。我不确定为什么会产生那种效果。如果有人能澄清,我会很感激。