python - 在 Pycharm、Python、Django 中使用函数名作为变量时出错:分配前引用了局部变量“已处理”
问题描述
我使用 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
解决方案
一种简单的解决方案是:
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)
推荐阅读
- c++ - QMediaPlayer 无法在 Window 上播放歌曲
- mysql - SQL GROUP_CONCAT 查询帮助
- java - 在 Android 中使用 ACTION_DIAL 可以同时拨打两个特殊符号
- intellij-idea - 如何使用预提交挂钩使用 IntelliJ 格式格式化代码?
- javascript - 需要在另一个 div 悬停时向 div 添加类
- vue.js - 如何解决在 shopware 中通过 Lightweight 方法创建的 2 个插件之间的冲突?
- c# - 如何创建服务绑定 HttpClient 的实例?
- javascript - 未捕获的 TypeError 无法读取属性“0”
- powerdns - PDNS 将未知条目转发到另一个名称服务器
- angular - FileReader:获取文件名