0

What I want to do.

I want to make an web app using Flask/Python3. What the web page shows the some words which is sent from this page(=form). In addition to this feature, when no words is sent the page only shows form.

Environment

  • Windows11 64bit
  • Python v3.10.10 64bit
  • Flask v2.2.3

Code

import os
from flask import Flask,request,render_template,url_for

app = Flask(__name__)

@app.route("/",methods=["POST","GET"])
def index():
    
    if request.form["test"] is None:
        res = "None"
    else:
        res = request.form["test"]
        
    BASE_HTML="""
    <!DOCTYPE html>
    <html lang='ja'>
    <head>
        <meta charset='utf-8'>
        <title>DEMO</title>
    </head>
    <body>
        <form action="{{ url_for("index") }}" method="POST">
            <input type='text' value='"""+res+"""'>
            <input type='submit' value="SEND">
        </form>
    </body>
    </html>
    """
    
    os.chdir("c:\\users\\username\\documents\\templates")
    with open("test.html",mode="w",encoding="utf-8") as f:
        f.write(BASE_HTML)

    return render_template("test.html")

if __name__ == '__main__':
    app.run(debug=True)

How the error happended

File "C:\Users\username\Documents\app.py", in index
if request.form["test"] is None:
File "C:\py64-31010\lib\site-packages\werkzeug\datastructures.py", in __getitem__
raise exceptions.BadRequestKeyError(key)

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'test'

How to make the code compatible with/without the data sent from form ?

I understand this error happens because there is no form data labeled 'test' but I don't want to prepare another page for without data sent from form. So how should I made code for that ?

kazutaka
  • 39
  • 1
  • 6
  • You could try testing if the form contains data labeled 'test' with this, `if 'test' in request.form:` instead of what you have, `if request.form["test"] is None:`. [This question](https://stackoverflow.com/q/1602934/15368978) covers that topic more clearly. – Patrick Yoder May 03 '23 at 07:04
  • 1
    Dear Patrick, Thank you for your advise ! That is what I really want to know. I really appreciate it ! – kazutaka May 03 '23 at 08:19

0 Answers0