Bootstrap FreeKB - Flask - GET the value from a POST form using request.form
Flask - GET the value from a POST form using request.form

Updated:   |  Flask articles

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

Let's say your flask project has the following structure.

├── main.py
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html

 

Let's say home.html has the following, to submit a POST request to the /Foo endpoint where the value will be in the "bar" input.

<form method="POST" action="/Foo">
  <input type="input" id="bar" name="bar">
  <button type="submit"></button>
</form>

 

requests can be used to submit a POST request to an API. pip install can be used to install requests.

pip install requests

 

Here is how you could print the value in the "bar" input that was POST to the /Foo endpoint.

import requests
@views.route('/Foo', methods=['GET', 'POST'])
def Foo():
    print(f"request.form['bar'] = {request.form['bar']}")

 

Better yet, with error handling.

import requests
@views.route('/Foo', methods=['GET', 'POST'])
def Foo():
    if request.form.get['bar'] != None:
      print(f"request.form.get['bar'] = {request.form.get['bar']}")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter b0b6c4 in the box below so that we can be sure you are a human.