在Pycharm,Python和Django中将函数名称用作变量时出错:赋值前引用了局部变量“ processed”

时间:2019-09-25 07:02:23

标签: python django variables pycharm

我使用Pycharm Professional 2019.2,Python 3.7.4,Django 2.2.5。 据我所知,函数名称是模块中的全局变量。但是我有一个否认这一点的函数。

def processed(request):
    if request.method == 'post':
        text = request.post['text']
        processed = text.upper()
    return HttpResponse(processed)

浏览器显示以下错误:

UnboundLocalError at /process/
local variable 'processed' referenced before assignment
Request Method: POST
Request URL:    http://127.0.0.1:8000/process/
Django Version: 2.2.5
Exception Type: UnboundLocalError
Exception Value:    
local variable 'processed' referenced before assignment

1 个答案:

答案 0 :(得分:1)

一个简单的解决方案是:

def processed(request):
    # Do not use the function name as the parameter name.
    ret = processed

    # It should be 'POST', not 'post'.
    if request.method == 'POST':
        # It should be 'POST', not 'post'.
        text = request.POST['text']
        ret = text.upper()

    return HttpResponse(ret)