C. Route decorator should not have methods argument
D. Function name cannot be 'data'
Solution
Step 1: Check syntax of if statement
The if statement lacks a colon at the end, causing a syntax error.
Step 2: Verify other parts
request.method is valid, methods argument is correct, function name is allowed.
Final Answer:
Missing colon after if statement -> Option A
Quick Check:
if statement needs colon [OK]
Hint: Check colons after if/else statements [OK]
Common Mistakes:
Forgetting colon after if
Thinking request.method is invalid
Misunderstanding methods argument
5. You want to create a Flask route '/submit' that accepts both GET and POST requests. When accessed by GET, it should show a form. When accessed by POST, it should process form data and return a confirmation message. Which code snippet correctly implements this behavior?
hard
A. from flask import Flask, request
app = Flask(__name__)
@app.route('/submit', methods=['GET', 'POST'])
def submit():
return 'Submit page'
B. from flask import Flask, request
app = Flask(__name__)
@app.route('/submit')
def submit():
if request.method == 'POST':
return 'Data received'
else:
return ''
C. from flask import Flask
app = Flask(__name__)
@app.route('/submit', methods=['POST'])
def submit():
return 'Only POST allowed'
D. from flask import Flask, request
app = Flask(__name__)
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
data = request.form.get('data')
return f'Data received: {data}'
else:
return ''''''
Solution
Step 1: Check methods argument
from flask import Flask, request
app = Flask(__name__)
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
data = request.form.get('data')
return f'Data received: {data}'
else:
return '''''' correctly uses methods=['GET', 'POST'] to accept both request types.
Step 2: Verify request method handling
from flask import Flask, request
app = Flask(__name__)
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
data = request.form.get('data')
return f'Data received: {data}'
else:
return '''''' checks request.method and returns form HTML for GET and processes form data for POST.
Step 3: Compare other options
The other options either miss methods argument, do not handle both methods properly, or do not return form on GET.
Final Answer:
The code snippet that uses methods=['GET', 'POST'], checks request.method, returns form for GET and processes data for POST -> Option D
Quick Check:
methods=['GET','POST'] + if request.method [OK]
Hint: Use methods=['GET','POST'] and check request.method [OK]
Common Mistakes:
Not specifying methods argument
Not checking request.method
Returning same response for all methods
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.