Consider this Flask route handling a POST form submission:
from flask import Flask, request
app = Flask(__name__)
@app.route('/submit', methods=['POST'])
def submit():
name = request.form.get('name', 'Guest')
return f'Hello, {name}!'If a form sends name=Alice in the POST data, what will the response be?
from flask import Flask, request app = Flask(__name__) @app.route('/submit', methods=['POST']) def submit(): name = request.form.get('name', 'Guest') return f'Hello, {name}!'
Check how request.form.get works with the given key.
The request.form.get('name', 'Guest') fetches the value of 'name' from the POST data. Since the form sends name=Alice, it returns 'Alice'. So the response is 'Hello, Alice!'.
Which of the following route decorators correctly allows a Flask route to accept POST requests?
Look at the correct parameter name and its expected type for methods.
The methods parameter expects a list of HTTP methods. So methods=['POST'] is correct. Other options have wrong parameter names or types.
Given this Flask route:
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
return f'User: {username}'When a POST request is sent without the 'username' field, what error occurs and why?
@app.route('/login', methods=['POST']) def login(): username = request.form['username'] return f'User: {username}'
Accessing a missing key in a dictionary-like object raises which error?
Using request.form['username'] tries to get the key directly. If the key is missing, it raises a KeyError. To avoid this, use request.form.get('username').
Consider this Flask app snippet:
from flask import Flask, request
app = Flask(__name__)
count = 0
@app.route('/increment', methods=['POST'])
def increment():
global count
count += 1
return str(count)If three POST requests are sent sequentially to '/increment', what will be the response to the third request?
from flask import Flask, request app = Flask(__name__) count = 0 @app.route('/increment', methods=['POST']) def increment(): global count count += 1 return str(count)
Think about how global variables behave across requests in a running Flask app.
The variable count is global and increments by 1 on each POST request. After three requests, it will be 3.
In a Flask app, why is it generally a bad idea to use global variables to store data from POST requests for tracking user state?
Consider how Flask handles multiple users and requests in production.
Flask apps often run with multiple threads or processes. Global variables are local to each process and not synchronized, so using them to store user state can cause inconsistent or lost data. Proper state management uses sessions or databases.