Flask-html:验证表单输入的最佳方式



你好,我正在尝试使用flask模块创建一个web注册表。检查用户名是否包含一定数量的字符、数字和大写字母的最简单方法/模块是什么?在这种情况下,如何循环表单输入,直到输入有效的用户名?

@app.route('/register', methods=['POST', 'GET'])
def register():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
error = None
if not username:
error = "Username is required."
elif not password:
error = "Password is required."
flash(error)
if error is None:
with open('data.txt', 'a', encoding='utf8') as file:
encoded_password = password.encode()
hash_password = hashlib.sha256(encoded_password).hexdigest()
file.write(username + ' ' + hash_password + 'n')
return redirect(url_for("login"))
return render_template('register.html')

调用另一个类似的函数(只是一个担心用户名的例子(,并根据您认为合适的方式扩展逻辑-根据process_registration是否为True来确定它们是否应该留在注册页面上

def verify_user_registration_credentials(username, password):
if not username:
flash_message = "Please enter a username"
process_registration = False
elif len(username) <= 5:
flash_message = "Please enter a username greater than 5 characters"
process_registration = False
else: 
for character in username:
if character.isdigit() or character.isupper():
break
process_registration = True # assuming you want them to have either a number or an upper case letter in their username

最新更新