request.params 中的关键错误

Key error in request.params

我是 Python 的初学者,我必须创建一个金字塔项目,它接受来自的用户输入,并执行一个简单的操作,将结果返回给用户。 这是我的 views.py

 from pyramid.response import Response
from pyramid.view import view_config
@view_config(route_name="home",renderer='templates/ui.pt')
def my_view(request):
    myvar=request.params['command']
    return Response(myvar)

这是我的 templates/ui.pt(不包括所有首字母 html,head 标签)

    <form action="my_view" method="POST"><input type="text" name="command"/>
<input type="submit" name="go" value="submit"/></form>
</html>

当我运行这个的时候,我得到这个错误 按键错误:'command'

请帮忙。

如果您的请求中没有传递任何参数(如果您访问该页面而没有发布或向查询字符串添加参数 -- http://mypage/my_view?command=something 就会发生这种情况),那么 request.params MultiDict 中不会有一个名为 'command' 的键,这就是您的错误来源。您可以明确检查 'command' 是否在您的 request.params:

myvar = None
if 'command' in request.params:
    myvar = request.params['command']

或者您可以(更常见)使用字典的 get 方法提供默认值:

myvar = request.params.get('command', None)

此外,由于您要为视图定义模板,通常,您的 return 值会为该模板提供上下文。但是,您的代码实际上并未使用模板,而是直接 return 响应。你通常不会那样做。你会做更多像这样的事情:

@view_config(route_name="home",renderer='templates/ui.pt')
def my_view(request):
    myvar=request.params.get('command',None)
    return {'myvar': myvar }

然后在您的模板中引用它传递的对象:

<!doctype html>
<html>
<body>
<form method="POST"><input type="text" name="command"/>
<input type="submit" name="go" value="submit"/></form>
<div tal:condition="myvar">
   You entered <tal:block tal:content="myvar"></tal:block>
</div>
</body>
</html>

这是一个从头开始的演练,以实现上述工作:

安装金字塔:

pip install pyramid

创建您的金字塔项目:

pcreate -t starter myproject

为您的项目设置环境:

cd myproject
python setup.py develop

将 myproject/views.py 替换为:

from pyramid.view import view_config

@view_config(route_name="home",renderer='templates/ui.pt')
def my_view(request):
    myvar=request.params.get('command',None)
    return {'myvar': myvar }

添加 myproject/templates/ui.pt 文件:

<!doctype html>
<html>
<body>
<form method="POST"><input type="text" name="command"/>
<input type="submit" name="go" value="submit"/></form>
<div tal:condition="myvar">
   You entered <tal:block tal:content="myvar"></tal:block>
</div>
</body>
</html>

启动您的应用程序:

pserve --reload development.ini

访问您的金字塔网站:

http://localhost:6543

初学者开始学习 Pyramid 的最佳地点是它的文档,特别是 Quick Tutorial

快速教程逐步介绍了通往 Web 表单的一系列主题。