Flask登录功能点击按钮触发KeyError错误的解决问询
解决Flask登录脚本的KeyError错误
开发基于Flask的Python登录脚本,访问链接显示用户名、密码输入框及登录按钮,预期点击登录后展示用户输入的账号信息。目前登录页面正常显示,但点击登录按钮触发KeyError错误。
原代码
from flask import Flask, request, redirect, url_for app = Flask(__name__) @app.route('/') def RedirectToLogin(): return redirect(url_for('login')) @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] return ''' <html> <head> <style> .details-container { display: flex; justify-content: center; align-items: center; height: 100vh; font-size: 24px; text-align: center; } .form-container { display: flex; flex-direction: column; width: 200px; margin: 0 auto; } .form-input { margin-bottom: 10px; } .smooth-button { border-radius: 12px; padding: 10px 20px; background-color: black; color: white; border: none; cursor: pointer; margin-top: 20px; } .smooth-button:hover { background-color: #45a049; } </style> </head> <body> <div class="details-container"> <div> <p>Username: {0}</p> <p>Password: {1}</p> </div> </div> </body> </html> '''.format(username, password) return ''' <html> <head> <style> .form-container { display: flex; flex-direction: column; width: 200px; margin: 0 auto; } .form-input { margin-bottom: 10px; } .smooth-button { border-radius: 12px; padding: 10px 20px; background-color: black; color: white; border: none; cursor: pointer; margin-top: 20px; } .smooth-button:hover { background-color: #45a049; } </style> </head> <body> <form method="post" action="/login" class="form-container"> <label for="username">Username:</label> <input type="text" id="username" name="username" class="form-input"><br> <label for="password">Password:</label> <input type="password" id="password" name="password" class="form-input"><br> <input type="submit" value="Login" class="smooth-button"> </form> </body> </html> ''' if __name__ == '__main__': app.run(debug=True)
实际报错
KeyError: '\n display' Traceback (most recent call last) File "C:\Users\ABC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\flask\app.py", line 1498, in __call__ return self.wsgi_app(environ, start_response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ABC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\flask\app.py", line 1476, in wsgi_app response = self.handle_exception(e) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ABC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\flask\app.py", line 1473, in wsgi_app response = self.full_dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ABC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\flask\app.py", line 882, in full_dispatch_request rv = self.handle_user_exception(e) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ABC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\flask\app.py", line 880, in full_dispatch_request rv = self.dispatch_request() ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ABC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\flask\app.py", line 865, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\ABC\Desktop\VsCode Projects\Python Projects\Login-Page-with-Flask.py", line 59, in login '''.format(username, password) ^^^^^^^^^^^^^^^^^^^^^^^^^^ KeyError: '\n display'
解决方案
错误原因
使用str.format()时,字符串中所有未被指定为占位符的{}会被当作要替换的键解析。POST返回的HTML中,CSS代码里的{ display: flex; }这类结构被format()误判为占位符键,导致抛出KeyError。
修改方法
将HTML/CSS中所有表示字面量的单个大括号{和}替换为双大括号{{和}},仅保留{0}、{1}作为格式化占位符。
修改后的代码
from flask import Flask, request, redirect, url_for app = Flask(__name__) @app.route('/') def RedirectToLogin(): return redirect(url_for('login')) @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] return ''' <html> <head> <style> .details-container {{ display: flex; justify-content: center; align-items: center; height: 100vh; font-size: 24px; text-align: center; }} .form-container {{ display: flex; flex-direction: column; width: 200px; margin: 0 auto; }} .form-input {{ margin-bottom: 10px; }} .smooth-button {{ border-radius: 12px; padding: 10px 20px; background-color: black; color: white; border: none; cursor: pointer; margin-top: 20px; }} .smooth-button:hover {{ background-color: #45a049; }} </style> </head> <body> <div class="details-container"> <div> <p>Username: {0}</p> <p>Password: {1}</p> </div> </div> </body> </html> '''.format(username, password) return ''' <html> <head> <style> .form-container {{ display: flex; flex-direction: column; width: 200px; margin: 0 auto; }} .form-input {{ margin-bottom: 10px; }} .smooth-button {{ border-radius: 12px; padding: 10px 20px; background-color: black; color: white; border: none; cursor: pointer; margin-top: 20px; }} .smooth-button:hover {{ background-color: #45a049; }} </style> </head> <body> <form method="post" action="/login" class="form-container"> <label for="username">Username:</label> <input type="text" id="username" name="username" class="form-input"><br> <label for="password">Password:</label> <input type="password" id="password" name="password" class="form-input"><br> <input type="submit" value="Login" class="smooth-button"> </form> </body> </html> ''' if __name__ == '__main__': app.run(debug=True)
其他替代方案
也可以改用f-string,此时需要将CSS中的{}转义为{{}},占位符直接用{username}和{password}:
# POST部分修改为: return f''' <html> <head> <style> .details-container {{ display: flex; justify-content: center; align-items: center; height: 100vh; font-size: 24px; text-align: center; }} <!-- 其他CSS同理转义大括号 --> </style> </head> <body> <div class="details-container"> <div> <p>Username: {username}</p> <p>Password: {password}</p> </div> </div> </body> </html> '''
内容的提问来源于stack exchange,提问作者BackOut
相关产品推荐
相关产品推荐

