BottlePy-返回TypeError:无法散列的类型:带有“%if”子句的“设置”

时间:2018-06-25 16:53:39

标签: python python-3.x bottle

我正在尝试使用Bottle和Python 3.6创建一个非常简单的HTML表单。我希望有一个带有两个选项的表单,但我希望能够直接从python发送默认选项到表单。

我的测试代码如下:

# -*- coding: utf-8 -*-

from bottle import route, template, request, post, run

@route('/')
def test_1():

    return template('test.html',
                    selected="F")

@post('/')
def response():
    pass

run(host='localhost', port=8409)

这将调用如下的HTML模板(保存为test.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>

    <form method="post" action="/">

        %if {{selected}} == "T":
            <input type="radio", name="sel", value="T" checked>T<br>
            <input type="radio", name="sel", value="F">F<br>
        %else:
            <input type="radio", name="sel", value="T">T<br>
            <input type="radio", name="sel", value="F" checked>F<br>
        %end

        <input type='submit' value='submit'>

    </form>
</body>
</html>

当我尝试运行它时,出现以下错误消息:

Traceback (most recent call last):
  File "C:\Users\Rogerio\Python VENV\lib\site-packages\bottle.py", line 862, in _handle
    return route.call(**args)
  File "C:\Users\Rogerio\Python VENV\lib\site-packages\bottle.py", line 1740, in wrapper
    rv = callback(*a, **ka)
  File "G:/My Drive/Data Technology/Python/temp.py", line 9, in test_1
    selected="F")
  File "C:\Users\Rogerio\Python VENV\lib\site-packages\bottle.py", line 3619, in template
    return TEMPLATES[tplid].render(kwargs)
  File "C:\Users\Rogerio\Python VENV\lib\site-packages\bottle.py", line 3409, in render
    self.execute(stdout, env)
  File "C:\Users\Rogerio\Python VENV\lib\site-packages\bottle.py", line 3396, in execute
    eval(self.co, env)
  File "G:\My Drive\Data Technology\Python\test.html", line 11, in <module>
    %if {{selected}} == "T":
TypeError: unhashable type: 'set'

似乎问题出在%if命令,但我不知道自己在做什么错。任何帮助将不胜感激!

还有,是否存在将默认值传递给表单的更“适当”的方法?

谢谢!

1 个答案:

答案 0 :(得分:1)

在瓶子模板中,{{foo}}语法用于输出。除非您要“打印”变量(如使用html将其发送到浏览器一样),否则不要使用它。

要使用%if,您可以照常引用变量:

%if selected == "T":