我正在为Flask应用程序分配一个函数,该函数根据index.html页面上表单中隐藏字段的值执行不同的操作。我只有两条路线:' /' (index.html)和' / process' (对index.html执行操作)。
当我在Flask中运行它时(在virtualenv中运行python server.py),然后单击按钮" Make Money"在index.html上,我收到此错误:
"类型错误 TypeError:' ImmutableMultiDict'对象不可调用"
有人可以告诉我如何从隐藏的输入中获得所需的值吗?
server.py的内容
import datetime
import random
from flask import Flask, render_template, redirect, request, session
app = Flask(__name__)
app.secret_key = 'fooBarBaz'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/process', methods=['GET','POST'])
def process():
if request.method == 'POST':
target = request.form('name')
if target == 'clothing':
new_money = random.randrange(10, 21)
session['balance'] += new_money
timestamp = datetime.datetime.now()
session['register'] += ("Received" + new_money + " dollars at " + timestamp.strftime("%Y/%m/%d %I:%M %p"))
return render_template('index.html')
app.run(debug=True)
index.html的内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div container>
<div class='balance'>
<p>Your balance: {{ session['balance'] }}</p>
</div>
<div class="shops">
<div class="clothing">
<h2>Clothing Store</h2>
<p>(earns 10 - 20 dollars)</p>
<form action="/process" method="post">
<input type="hidden" name="clothing">
<input type="submit" value="Make Money!">
</form>
</div>
</div>
<div class="register">
<h4>Receipt Tape</h4>
<p>{{ session['register'] }}</p>
</div>
</div>
</body>
</html>
答案 0 :(得分:1)
表单应如下所示,并为隐藏输入定义值:
<form action="/process" method="post">
<input type="hidden" name="clothing" value="clothing">
<input type="submit" value="Make Money!">
</form>
在不改变逻辑的情况下,寄存器部分可以接受html标记来呈现换行符
<p>{{ session['register']|safe }}</p>
然后,只需进行少量更改,您就可以解决视图中遇到的一些问题。为了避免未声明session
密钥的错误,最好的方法是使用方法get
与0
或""
而不是None
时返回找不到密钥:
@app.route('/process', methods=['GET','POST'])
def process():
if request.method == 'POST':
target = request.form.get('clothing')
if target == 'clothing':
new_money = random.randrange(10, 21)
session['balance'] = session.get('balance',0) + new_money
timestamp = datetime.datetime.now()
session['register'] = "{}<br>Received {} dollars at {}".format(
session.get('register',''),
new_money,
timestamp.strftime("%Y/%m/%d %I:%M %p"))
return render_template('index.html')