為我對這個問題的無知表示歉意。我剛剛接觸了使用 Python 和 Flask 的 Web Dev。我正在嘗試創(chuàng)建一個應用程序,該應用程序?qū)妮斎胱侄沃蝎@取字符串并將其轉(zhuǎn)換為哈希值并將其顯示在輸出頁面上。但是,我不確定我的表單是否設置正確。當我運行應用程序時,它只返回一個假值,并顯示即使我輸入隨機字符串,用戶也沒有輸入任何內(nèi)容。應用程序from flask import Flask, render_template, request, url_for, flash, redirectfrom message import MessageForm, validators, ValidationErrorfrom cryptography.fernet import Fernetapp = 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)消息.pyfrom wtforms import StringField, SubmitField, validatorsfrom flask_wtf import FlaskFormfrom wtforms.validators import DataRequired, ValidationErrorclass 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 %}我想要的是,如果沒有輸入任何內(nèi)容,則讓應用程序返回錯誤,但如果輸入內(nèi)容,則正確運行應用程序。我希望這是有道理的,如前所述,請原諒我的無知。非常感激你的幫助。
2 回答

寶慕林4294392
TA貢獻2021條經(jīng)驗 獲得超8個贊
在 HTML 表單中,嘗試將 csrf_token 放在表單聲明之后,如下所示:
<br />
<form action="/" method="POST">
{{ form.csrf_token }}
<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>

絕地無雙
TA貢獻1946條經(jīng)驗 獲得超4個贊
也許你可以試試:
user_message = request.form.get("message")
代替
user_message = form.message_field.data
添加回答
舉報
0/150
提交
取消