Flask 表单仅返回 FALSE 的问题

为我对这个问题的无知表示歉意。我刚刚接触了使用 Python 和 Flask 的 Web Dev。


我正在尝试创建一个应用程序,该应用程序将从输入字段中获取字符串并将其转换为哈希值并将其显示在输出页面上。但是,我不确定我的表单是否设置正确。


当我运行应用程序时,它只返回一个假值,并显示即使我输入随机字符串,用户也没有输入任何内容。


应用程序

from flask import Flask, render_template, request, url_for, flash, redirect

from message import MessageForm, validators, ValidationError

from cryptography.fernet import Fernet


app = Flask(__name__)

app.secret_key = 'development'


key = Fernet.generate_key()

f = Fernet(key)


@app.route('/', methods=['GET', 'POST'])

def home():

    form = MessageForm(request.form)


if request.method == 'POST' and form.validate_on_submit():

    user_message = form.message_field.data

    e = user_message.encode(encoding='UTF-8')

    token = f.encrypt(e)

    output = bytes.decode(token)

    return redirect('output.html', output=output)


return render_template('index.html', form=form)


if __name__ == ('__main__'):

    app.run(debug=True)

消息.py

from wtforms import StringField, SubmitField, validators

from flask_wtf import FlaskForm

from wtforms.validators import DataRequired, ValidationError


class MessageForm(FlaskForm):

    message_field = StringField('Please enter the message you would like to 

    encrypt:', [validators.Required('Please enter a message!')])

    submit = SubmitField('Submit')

HTML 表单

{% extends 'layout.html' %}


{% block body %}


{{ form.csrf_token }}


<br />

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

    <div class="form-group">

        <label style="font-weight: bold;">{{ form.message_field.label }}</label>

        <input type="text" class="form-control" name="message" id="message">

        <br />

        <button type="submit" class="btn btn-primary btn-lg btn-block">Encrypt Message</button>

    </div>

</form>


{% for message in form.message_field.errors %}

    <div class="alert alert-danger" role="alert">

        {{ message }}

    </div>

{% endfor %}   


{% endblock %}

我想要的是,如果没有输入任何内容,则让应用程序返回错误,但如果输入内容,则正确运行应用程序。


我希望这是有道理的,如前所述,请原谅我的无知。


非常感激你的帮助。


潇湘沐
浏览 165回答 2
2回答

宝慕林4294392

在 HTML 表单中,尝试将 csrf_token 放在表单声明之后,如下所示:<br /><form action="/" method="POST">&nbsp; &nbsp; {{ form.csrf_token }}&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <label style="font-weight: bold;">{{ form.message_field.label }}</label>&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" class="form-control" name="message" id="message">&nbsp; &nbsp; &nbsp; &nbsp; <br />&nbsp; &nbsp; &nbsp; &nbsp; <button type="submit" class="btn btn-primary btn-lg btn-block">Encrypt Message</button>&nbsp; &nbsp; </div></form>

绝地无双

也许你可以试试:user_message&nbsp;=&nbsp;request.form.get("message")代替user_message&nbsp;=&nbsp;form.message_field.data
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python