Bad Request Error with flask, python, HTML, unusual initialization behavior with flask.request.form
The issue here is that you are attempting to access POST
ed variables in a method that will only handle GET
requests. When you attempt to access a query string or POST parameter that is not set Flask will, by default, raise a BadRequest
error (because you are asking for something that the person hitting the page did not supply).
What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. You can catch it like a standard KeyError but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.
If you need to access a variable from either request.args
(GET) or request.form
(POST) and you don't need it to be set use the get
method to get the value if it is there (or None
if it is not set.
# Will default to Noneyour_var = request.form.get("some_key")# Alternately:your_var = request.form.get("some_key", "alternate_default_value")
Here's an alternate way of structuring your code:
import sysimport flask, flask.viewsapp = flask.Flask(__name__)app.secret_key = "bacon"app.debug = Trueclass View(flask.views.MethodView): def get(self): """Enable user to provide us with input""" return self._default_actions() def post(self): """Map user input to our program's inputs - display errors if required""" result = flask.request.form['result'] # Alternately, if `result` is not *required* # result = flask.request.form.get("result") return self._default_actions(result=result) def _default_actions(self, result=None): """Deal with the meat of the matter, taking in whatever params we need to get or process our information""" if result is None: return flask.render_template("test.html") else: return flask.render_template("test.html", result=result)app.add_url_rule('/', view_func=View.as_view('main'), methods=['GET', 'POST'])if __name__ == "__main__": app.run()