There are 3 methods of getting user data from a view to a controller.
- URL query parameters
URL query parameters are listed as key-value pairs at the end of a URL, preceding a “?” question mark. E.g. www.example.com/hello?my_key=my_value.
value1 = request.args.get('my_key')
value2 = request.args.get('foo', 'my default')
- Forms
request.form.get(name) reads the value from a form input control (text input, number input, password input, etc) by the name attribute on the input HTML element.
username = request.form.get('username')
password = request.form.get('password')
result = request.form.get('foo', 'my default')
- JSON
request.data retrieves JSON as a string. Then we’d take that string and turn it into python constructs by calling json.loads on the request.data string to turn it into lists and dictionaries in Python.
For data type application/json, use request.data
data_string = request.data
data_dictionary = json.loads(data_string)
Using HTML form submission to get the data
- Forms take an action (name of the route) and method (route method) to submit data to our server.
- The name attribute on a form control element is the key used to retrieve data from request.get(key).
- All forms either define a submit button, or allow the user to hit ENTER on an input to submit the form.
<input type="text" value="foo2" id="bar1" name="bar2" class="bar3">
request.form.get('bar2')
Form methods POST vs GET
Using the POST method, then you should use the request.form.get(name)
Using the GET method, then you should use the value1 = request.args.get(‘my_key’)
“Response body” should be corrected to “Request body”, throughout, since the client is sending off a request.
The way form data traverses from the client to server differs based on whether we are using a GET or a POST method on the form.
The POST submission
- On submit, we send off an HTTP POST request to the route /create with request body
- The request body stringifies the key-value pairs of fields from the form (as part of the name attribute) along with their values.
The GET submission
- Sends off a GET request with URL query parameters that appends the form data to the URL
- Ideal for smaller form submission.
Notes: POSTs are ideal for longer form submissions, since URL query parameters can only be so long compared to request bodies (max 2048 characters). Moreover, forms can only send POST and GET requests, and nothing else.