Flask Web Framework: past questions

39 questions · 121 marks · 10 papers. Try each one before checking.

Solve them and check answers →Read the notes first

24 Mar 2024

Question 3 MCQ · 2 marks

Consider the following Flask code snippet.

from flask import Flask, request

app = Flask(__name__)
@app.route('/greet/<name>')
def greet(name):
    if name:
        return f'<h1>Hi, Mr/Ms/ {name} welcome to flask</h1>'
    else:
        return f'<h1>Hi, Mr/Ms/ <Unknown> welcome to flask</h1>'

app.run(debug=True)

If the application is running on a local server for the URL: https://127.0.0.1:5000, what will the browser render for the URL. http://127.0.0.1:5000/greet/?

  1. Hi, Mr/Ms/None welcome to flask
  2. Hi, Mr/Ms/ welcome to flask
  3. Bad request, Invalid name provided
  4. Not Found

Question 13 MSQ · 3 marks

Consider the following flask application. app.py

from flask import Flask, abort, request

app = Flask(__name__)

@app.route('/process')
def process():
    username = request.args.get('uname', 'MAD-I')
    if username.isnumeric():
        abort(400, "Bad Request: Numeric username provided")
    return f'<h1>Valid Username: {username}</h1>'

app.run(debug=True)

Which of the following statements is/are true if the application is running locally on http://127.0.0.1:5000 ?

  1. For URL http://127.0.0.1:5000?uname=MAD-II the browser will render Valid Username: MAD-II
  2. For URL http://127.0.0.1:5000/process the browser will render Valid Username: MAD-I
  3. For URL http://127.0.0.1:5000/process?uname the browser will render Valid Username:
  4. For URL http://127.0.0.1:5000/process?uname=101MU the browser will render Bad Request: Numeric username provided

Question 14 MSQ · 3 marks

Consider the following flask application. app.py

from flask import Flask, abort, request

app = Flask(__name__)
data = {'MAD-I':'CS2003', 'MAD-II':'CS2004', 'Java':'CS2005'}
@app.route('/course/<course_name>')
def course(course_name):
    course_id = request.args.get('id')
    if course_name in data and course_id == data[course_name]:
        return f'<h1>The Course ID for {course_name} is: {course_id}</h1>'
    else:
        abort(400, "Bad Request: Invalid data")

app.run(debug=True)

Which of the following statements is/are true if the application is running locally on http://127.0.0.1:5000 ?

  1. For URL http://127.0.0.1:5000/MAD-I?id=CS2003 the browser will render; The Course ID for MAD-I is: CS2003
  2. For URL http://127.0.0.1:5000/course/Java?id=CS2005 the browser will render; The Course ID for Java is: CS2005
  3. For URL http://127.0.0.1:5000/course?course_name=MAD-II&id=CS2004 the browser will render; The Course ID for MAD-II is: CS2004
  4. For URL http://127.0.0.1:5000/course/MAD-II?id=CS2003 the browser will render; Bad Request: Invalid data

Question 2 MCQ · 2 marks

Consider the following code.

from flask import Flask
app = Flask(__name__)

@app.route('/home')
def home1():
    return "This is homepage 1"

@app.route('/home/')
def home2():
    return "This is homepage 2"

@app.errorhandler(404)
def page_not_found(e):
    return 'page not found'

app.run(debug=True)

If the flask application is running on http://127.0.0.1:5000, what will browser render for URL http://127.0.0.1:5000/home/

  1. Page not found
  2. This is homepage 1
  3. This is homepage 2
  4. Code will throw error

Question 12 MSQ · 3 marks

Consider the following flask application. app.py

from flask import Flask, abort, request

app = Flask(__name__)

@app.route('/validate/<int:number>')
def validate_number(number):
    if number % 2 == 0 and number % 3 == 1:
        abort(400, "Bad Request: Invalid number provided")
    return f'<h1>Valid Number: {number}</h1>'

app.run(debug=True)

Which of the following statements is/are true if the application is running locally on http://127.0.0.1:5000 ?

  1. For URL http://127.0.0.1:5000/validate/4 the browser will render Valid Number: 4
  2. For URL http://127.0.0.1:5000/validate?number=5 the browser will render Bad Request: Invalid number provided
  3. For URL http://127.0.0.1:5000/validate/4 the browser will render Bad Request: Invalid number provided
  4. For URL http://127.0.0.1:5000/validate/5 the browser will render Valid Number: 5

04 Aug 2024

Question 7 MSQ · 3 marks

Consider the following flask application.

from flask import Flask, request

app = Flask(__name__)

@app.route('/home')
def home():
    var_a = request.args.get('method')
    if var_a == "GET":
        return """
        <body style="background-color: lightgray; color: purple; text-align: center; font-weight: bold;">
            <p>IIT</p>
            <p>MADRAS</p>
        </body>
        """
    elif var_a == "POST":
        return """
        <body style="background-color: lightgray; color: purple; text-align: center; font-weight: bold;">
            <p>IIT</p>
            <span>MADRAS</span>
        </body>
        """
    else:
        return "Invalid Method"

app.run(debug=True)

If the application is running locally on http://127.0.0.1:5000 then which of the following statements are correct?

  1. The browser will render aesthetically similar output for http://127.0.0.1:5000/home?method=POST and http://127.0.0.1:5000/home?method=GET
  2. The browser will render aesthetically different output for http://127.0.0.1:5000/home?method=POST and http://127.0.0.1:5000/home?method=GET
  3. The browser will render Method Not Allowed error for http://127.0.0.1:5000/home
  4. The browser will render Invalid Method error for http://127.0.0.1:5000/home

Question 11 COMP · 2 marks

What will be the output given by browser if the application is run with command python app.py Application Development DBMS on terminal with URL http://127.0.0.1:5000?course=DBMS ?

  1. Welcome to Application Development!
  2. Welcome to DBMS!
  3. Invalid Data
  4. Not Found

Question 10 COMP · 3 marks

What should be the code to run the application, and the URL respectively such that the browser gives output as: Welcome to Application Development!?

  1. Code: python app.py Application Development Java URL: http://127.0.0.1:5000/course?course=Java
  2. Code: python app.py Application Development Java URL: http://127.0.0.1:5000/course=Application Development
  3. Code: python app.py "Application Development" Java URL: http://127.0.0.1:5000/course?course=Java
  4. Code: python app.py "Application Development" DBMS URL: http://127.0.0.1:5000/course?course=Application Development

Question 14 COMP · 3 marks

Which of the following URLs will trigger the "get_user" controller in the given application.

  1. http://127.0.0.1:5000/104
  2. http://127.0.0.1:5000/user/104
  3. http://127.0.0.1:5000?id=104
  4. http://127.0.0.1:5000/user?id=104

Question 13 COMP · 3 marks

Which of the following is/are the correct URLs for retrieving the user from the database with "id": "103"?

  1. http://127.0.0.1:5000/103
  2. http://127.0.0.1:5000/user/103
  3. http://127.0.0.1:5000?id=103
  4. http://127.0.0.1:5000/user?id=103

Question 18 MSQ · 2 marks

Consider the following flask application. app.py

from flask import Flask, abort, request
app = Flask(__name__)

@app.route('/login/<id>')
def login(id):
    if id:
        if id.isalpha():
            abort(400, "Bad Request: Invalid ID")
        return f'<h1>Your ID is: {id}</h1>'
    return f'<h1>Invalid ID</h1>'

app.run(debug=True)

Which of the following statements is/are true if the application is running locally on http://127.0.0.1:5000 ?

  1. For URL http://127.0.0.1:5000/login?id=MAD-I the browser will render Bad Request: Invalid ID
  2. For URL http://127.0.0.1:5000/login/ the browser will render Invalid ID
  3. For URL http://127.0.0.1:5000/login/CS2003 the browser will render Your ID is: CS2003
  4. For URL http://127.0.0.1:5000/login/PDSA the browser will render Bad Request: Invalid ID

01 Dec 2024

Question 9 MSQ · 3 marks

Consider the flask code below.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def get_home():
    a = [i for i in range(11)]
    t = ", ".join(map(str, a))
    return t

@app.route("/numbers/<int:n>")
def get_numbers(n):
    a = [i for i in range(n + 1)]
    t = ", ".join(map(str, a))
    return t

if __name__ == "__main__":
    app.run(debug=True)

Assume that the above flask application is running on http://127.0.0.1:5000. Which of the following statements is/are True for the above code snippet?

  1. URL: http://127.0.0.1:5000/ Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  2. URL: http://127.0.0.1:5000/numbers/5 Output: 0, 1, 2, 3, 4, 5
  3. URL: http://127.0.0.1:5000/7 Output: 0, 1, 2, 3, 4, 5, 6, 7
  4. URL: http://127.0.0.1:5000/7 Output: Not Found

Question 7 MSQ · 3 marks

Consider the following HTML document "form.html" and the flask route given in "app.py". Assume all the required methods are imported, Which of the following statements is/are correct.

Filename: form.html

<!DOCTYPE html>
<html>
<head>
<style>
    input:valid {border: 2px solid red;}
</style>
</head>
<body>
    <form action="/submit_form" method="post">
        <label for="e-mail">Please enter your email address</label>
        <input id="e-mail" name="e-mail" required/>
        <button>Submit</button>
    </form>
</body>
</html>

Filename: app.py

@app.route('/submit_form', methods = ['GET', 'POST'])
def form_on_submit():
    if request.method == 'POST':
        email = request.form.get('e-mail')
        if "@" in email:
            return "Form is validated"
    return render_template('form.html')

  1. The above HTML document has frontend validation incorporated, usingHTML5 form validation.
  2. The above HTML document has only backend validation incorporated.
  3. The above HTML document has both frontend and backend validationincorporated.
  4. If the e-mail input field is left blank, the border colour of the input field will bered.

Question 6 MSQ · 3 marks

Consider the following flask application. app.py

from flask import Flask, abort, request

app = Flask(__name__)
data = {'PDSA':'CS2003', 'DBMS':'CS2004', 'Java':'CS2005'}
@app.route('/course/<course_name>')
def course(course_name):
    course_id = request.args.get('id')
    if course_name in data and course_id == data[course_name]:
        return f'<h1>The Course ID for {course_name} is: {course_id}</h1>'
    else:
        abort(400, "Bad Request: Invalid data")

app.run(debug=True)

Which of the following statements is/are true if the application is running locally on http://127.0.0.1:5000 ?

  1. For URL http://127.0.0.1:5000/PDSA?id=CS2003 the browser will render; Not Found
  2. For URL http://127.0.0.1:5000/course/Java?id=CS2005 the browser will render; The Course ID for Java is: CS2005
  3. For URL http://127.0.0.1:5000/course?course_name=DBMS&id=CS2004 the browser will render; The Course ID for DBMS is: CS2004
  4. For URL http://127.0.0.1:5000/course/DBMS?id=CS2003 the browser will render; Bad Request: Invalid data

Question 5 MSQ · 3 marks

Consider the following flask application. app.py

from flask import Flask, abort, request
app = Flask(__name__)

@app.route('/login/<id>')
def login(id):
    if id:
        if id.isalnum():
            abort(400, "Bad Request: Invalid ID")
        return f'<h1>Your ID is: {id}</h1>'
    return f'<h1>Invalid ID</h1>'

app.run(debug=True)

Which of the following statements is/are true if the application is running locally on http://127.0.0.1:5000 ?

  1. For URL http://127.0.0.1:5000/login?id=MAD-I the browser will render Not Found
  2. For URL http://127.0.0.1:5000/login/ the browser will render Invalid ID
  3. For URL http://127.0.0.1:5000/login/CS2003 the browser will render Bad Request: Invalid ID
  4. For URL http://127.0.0.1:5000/login/PDSA the browser will render Bad Request: Invalid ID

16 Mar 2025

Question 12 MSQ · 2 marks

Consider the flask code below.

from flask import Flask
app = Flask(__name__)

@app.route("/user/<id>")
def get_user(id):
    return "User Id : " + str(id)

if __name__ == "__main__":
    app.run(debug=True)

Assume that the above flask application is running on http://127.0.0.1:5000. Which of the following URLs will render "Not Found" error?

  1. http://127.0.0.1:5000/user/2001
  2. http://127.0.0.1:5000/user/id=2001
  3. http://127.0.0.1:5000/id=2001
  4. http://127.0.0.1:5000/2001

Question 15 MSQ · 3 marks

Consider the following Flask application:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to Home Page"

@app.route('/user/<name>')
def user(name):
    return f"Hello, {name}!"

@app.route('/profile/<int:user_id>')
def profile(user_id):
    return f"User Profile ID: {user_id}"

if __name__ == "__main__":
    app.run(debug=True)

Assume the Flask application is running on http://127.0.0.1:5000/. Which of the following statements about this application are correct?

  1. Accessing http://127.0.0.1:5000/user/John will return: Hello, John!
  2. Accessing http://127.0.0.1:5000/user/07 will return: Hello, !
  3. Accessing http://127.0.0.1:5000/profile/10 will return: User Profile ID: 10
  4. Accessing http://127.0.0.1:5000/user/ will result in a 404 error.

Question 17 MSQ · 4.5 marks

Consider the following flask application. app.py

from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route("/if")
def ifelse():
    user = "MAD I"
    return f" Welcome {user}!"

@app.route("/for")
def for_loop():
    user = "MAD II"
    return f" Welcome {user}!"

@app.route("/choice/<pick>")
def choice(pick):
    if pick == 'if':
        return url_for('ifelse')
    if pick == 'for':
        return (url_for('for_loop'))

if __name__ == "__main__":
    app.run(debug=False)

Which of the following statements is/are true if the application is running locally on http://127.0.0.1:5000?

  1. For URL, http://127.0.0.1:5000/choice/for browser will display Welcome MAD II! as output
  2. For URL, http://127.0.0.1:5000/choice/if browser will render Welcome MAD I! as output
  3. For URL http://127.0.0.1:5000/choice/for browser will display /for as output.
  4. For URL http://127.0.0.1:5000/choice/if browser will display /if as output.

Question 7 MCQ · 3 marks

Consider the following Flask code.

from flask import Flask, request

app = Flask(__name__)

def is_odd(e):
    return e % 2 == 0

@app.route("/response")
def get_response():
    if request.args.get("n"):
        n = request.args.get("n")
        r = ""
        for i in range(1, (int(n) + 1)):
            if is_odd(i):
                r = r + "odd : " + str(i) + "\n"
            else:
                r = r + "even : " + str(i) + "\n"
        return r
    else:
        return "missing parameter `n` with value"

if __name__ == "__main__":
    app.run(debug=True)

Assume the above code is running on http://127.0.0.1:5000 . Which of the following request URL does not throw Not Found error?

  1. http://127.0.0.1:5000/response/n=6
  2. http://127.0.0.1:5000/response/
  3. http://127.0.0.1:5000/response&n=6
  4. http://127.0.0.1:5000/response?n=6

Question 13 MSQ · 3 marks

Consider the following flask application running locally on http://127.0.0.1:5000.

from flask import Flask, request
app = Flask(__name__)

@app.route('/endpoint/<username>')
def func(username):
    return {
        "username": username
    }, 200

@app.errorhandler(404)
def notfound(error):
    return {
        "message": "invalid endpoint!"
    }

app.run(debug = True)

Which of the following statements is/are correct for the URL: http://127.0.0.1:5000/endpoint/user1/developer

  1. The output on the browser will be: { "Username" : "user1" }
  2. The output on the browser will be: { "message": "invalid endpoint!" }
  3. The status code of the response will be 200
  4. The status code of the response will be 404

03 Aug 2025

Question 9 MCQ · 3 marks

Consider the following Flask app code.

from flask import Flask, request
valid_users = [
    {"uid": "student", "pwd": "12345"},
    {"uid": "professor", "pwd": "54321"},
    {"uid": "hod", "pwd": "abcde"},
]

app = Flask(__name__)

@app.route("/signin")
def login():
    args = request.args
    for vu in valid_users:
        if vu["uid"] == args["uid"] and vu["pwd"] == args["pwd"]:
            return "You are authorized!!"
        else:
            return "You are unauthorized!!"

app.run(debug=True)

Assume the above flask app runs on “http://127.0.0.1:5000/” and is accessed through the web browser. What will be the output for the URL: “http://127.0.0.1:5000/signin?uid=professor&pwd=54321” ?

  1. You are authorized!!
  2. You are unauthorized!!
  3. Not Found
  4. Internal Server Error

Question 11 MCQ · 4.5 marks

Consider the following flask application.

from flask import Flask, abort
app = Flask(__name__)

users = ["admin", "user_1", "user_2", "user_3"]

@app.route('/home/<string:username>', methods = ['POST'])
def home (username):
    if username in users:
        return f"<h1>Hello {username}, Welcome!</h1>"
    else:
        abort (407)

@app.errorhandler(404)
def user_error_1(error):
    return "<h1>The user you are looking for is invalid.</h1>"

@app.errorhandler(405)
def user_error_2(error):
    return "<h1>Please check the web request.</h1>"

@app.errorhandler (407)
def user_error_4(error):
    return "<h1>Proxy authentication required.</h1>"

app.run()

If the application is running locally on http://127.0.0.1:5000. What will be rendered on the browser for the URL http://127.0.0.1:5000/home/user_4?

  1. Hello user_4, Welcome!
  2. The user you are looking for is invalid.
  3. Not Found
  4. Please check the web request

14 Aug 2026

Question 8 MSQ · 5 marks

Consider the following flask app.

from flask import Flask, abort, redirect, url_for
app = Flask(__name__)

@app.route('/course/<path:subject>')
def course(subject):
    if "Python" in subject:
        return "Welcome to Python course!"
    else:
        abort(404)

@app.route('/learn/<path:subject>')
def learn(subject):
    if "Python" in subject:
        return redirect(url_for('course', subject=subject))
    else:
        abort(404)

@app.errorhandler(404)
def not_found(error):
    return "<h2>Course not available!</h2>"

app.run(debug=True)

If the application is running locally on http://127.0.0.1:5000, select the correct options.

  1. For the URL: http://127.0.0.1:5000/learn/web/Python?level=advanced The browser will render: Course not available!
  2. For the URL: http://127.0.0.1:5000/course/ML/Python?topic=NLP The browser will render: Welcome to Python course!
  3. For the URL: http://127.0.0.1:5000/learn/basics/Python?level=beginner The browser will render: Welcome to Python course!
  4. For the URL: http://127.0.0.1:5000/course/Java/React?type=Framework The browser will render: Course not available!

July 2022

Question 2 MSQ · 3 marks

Consider the Python file and a template given below. Python file: app.py

from flask import Flask, url_for, redirect, render_template

app = Flask(__name__)

@app.route("/<name>/")
def index1(name):
    return "Hi" + " " + name + "!" + " " + "This is your home page."

@app.route("/first_index/<string:name>")
def index2(name):
    if name == "XYZ":
        return redirect(url_for("index1", name = "XYZ"))
    else:
        return redirect(url_for("index3"))

@app.route("/second_index")
def index3():
    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True)

Template file: index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>My Document</title>
</head>
<body>
    <h2> You are on the incorrect page.</h2>
    <a href="{{ url_for("index1", name="ABC") }}">Go back</a>
</body>
</html>

If the above flask application is running locally on the URL 'http://127.0.0.1:5000', which of the following statements is/are true about the above code snippet?

  1. For the endpoint '/XYZ/' , the browser will show 'Not Found' error.
  2. On clicking the link "Go back" in "index.html", the browser will render: Hi ABC! This is your home page.
  3. For the endpoint '/first_index/XYZ', the browser will redirect to the URL for the function index3, i.e., '/second_index'.
  4. For the endpoint '/first_index/ABC', the browser will redirect to the URL for the function 'index3' i.e., '/second_index'.

Aug 2023

Question 2 MCQ · 2 marks

Consider the following flask application and select the correct option if the application is running locally on http://127.0.0.1:5000.

from flask import Flask
app = Flask (__name__)

@app.route('/work')
@app.route('/home')
def my_task():
    return "<h1>Hello! Reporting for my task</h1>"

app.run()

  1. The application will return 200 OK status code for /home endpoint only
  2. The application will return 200 OK status code for /work endpoint only
  3. The application will return 200 OK status code for both the endpoints
  4. The application will throw an AssertionError for both the endpoints

Question 14 MSQ · 4.5 marks

Consider the following flask app. Given that test_request_context() allows text to be printed on the terminal, which of the following statements is/are correct?

from flask import Flask, url_for

app = Flask (__name__)

@app.route('/home')
def index():
    return 'Mad-I welcomes you!'

@app.route('/user/<username>')
def profile(username):
    return f'{username}\'s profile'

with app.test_request_context():
    #== print statement ==#

  1. If #== print statement ==# is replaced by print(url_for('home')), the output on the terminal will be Mad-I welcomes you!.
  2. If #== print statement ==# is replaced by print(url_for('profile', username='Harry')), the output on the terminal will be /user/Harry
  3. If #== print statement ==# is replaced by print(url_for('profile', username='Harry', next='course')), the output on the terminal will be /user/Harry/course
  4. If #== print statement ==# is replaced by print(url_for('index', username='Harry')), the output on the terminal will be /home?username=Harry

Question 17 SA · 3 marks

Consider the following flask application.

from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/admin')
def hello_admin():
    return 'Hello Admin'

@app.route('/guest/<guest>')
def hello_guest(guest):
    return 'Hello ' + guest + ' as Guest'

@app.route('/user/<name>')
def hello_user(name):
    if name == 'admin':
        return redirect(url_for('hello_admin'))
    else:
        return redirect(url_for('hello_guest', guest = name))

if __name__ == '__main__':
    app.run(debug = True)

If this flask app is running locally on http://localhost:5000, what is the output for the following URL? For input: http://localhost:5000/user/admin?guest=appdev1

Type your answer on the interactive page.

Question 13 MSQ · 4.5 marks

Consider the following route in the flask for a signup page and select the correct option.

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    if request.method == 'GET':
        return """<form action='/signup' method= 'POST'>
        <label for='username'>Username</label>
        <input type='text' name='username' required>
        <label for='password' >Password</label>
        <input type='text' name='password' required minlength="8">
        <input type='submit' value='Submit'>
        </form>
        """
    if request.method == 'POST':
        if request.form.get('username') is None:
            return redirect(url_for(signup))
        if request.form.get('password') is None:
            return redirect(url_for(signup))
        if len(request.form.get('password')) < 8:
            return redirect(url_for(signup))
        return f"<h1>Welcome, {request.form.get('username')}!</h1>"

  1. The signup page is dynamically generated.
  2. The signup page uses server-side rendering.
  3. The signup page uses frontend validation only.
  4. The signup page uses backend validation.

Question 5 MCQ · 2 marks

Consider the following view function.

@app.route('/student', methods = ['GET', 'POST'])
def show_student():
    std = request.args
    details = {
        'Department': std['dept'],
        'Course-level': std['level'],
        'Course': std['course']
    }
    return details

If this flask app is running locally on http://127.0.0.1:5000, which of the following URLs will be handled by the controller correctly?

  1. http://127.0.0.1:5000/student/Electrical/Diploma/MAD1
  2. http://127.0.0.1:5000/Electrical/Diploma/MAD1
  3. http://127.0.0.1:5000/student?dept=Electrical&level=Diploma&course=MAD1
  4. http://127.0.0.1:5000?endpoint=student&dept=Electrical&level=Diploma&course=MAD1

Question 16 MSQ · 3 marks

Consider the following flask application.

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def out():
    val = request.args
    if val['num'] == '':
        return "<html><body> <h1>Invalid number</h1></body></html>"
    elif val['num'].isalpha()==True:
        return "<html><body><h1>Enter a valid number</h1></body></html>"
    else:
        out = int(val['num']) * int(val['num'])
        return f'<html><body> <h1>The output is {out}</h1></body></html>'

if(__name__ == "__main__"):
    app.run(debug=True)

If this flask app is running locally on http://localhost:5000, then which of the following statements is/are correct?

  1. For URL: http://localhost:5000/?num=abc Output is: Invalid number
  2. For URL: http://localhost:5000/?num=abc Output is: Enter a valid number
  3. For URL: http://localhost:5000/?num= Output is: Invalid number
  4. For URL: http://localhost:5000/?num=12 Output is: The output is 1212

Question 9 MCQ · 3 marks

Consider the following code.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def generate1():
    return "This is generate1"

@app.route('//')
def generate2():
    return "This is generate2"

@app.errorhandler(404)
def page_not_found(e):
    # setting 404 status explicitly
    return 'page not found'

app.run()

If the flask application is running on http://127.0.0.1:5000, what will browser render for URL http://127.0.0.1:5000//

  1. Page not found
  2. This is generate2
  3. This is generate1
  4. Code will throw error

Dec 2023

Question 4 MSQ · 3 marks

Consider the following flask app. Given that test_request_context() allows text to be printed on the terminal, which of the following statements is/are correct?

from flask import Flask, url_for
app = Flask (__name__)

@app.route('/home')
def index():
    return 'Mad-I Student Data'

@app.route('/student/<student_name>/<int:student_id>')
def profile(student_name, student_id):
    return f'Student Name: {student_name}, Student ID: {student_id}'

with app.test_request_context():
    #== print statement ==#

  1. If #== print statement ==# is replaced by; print(url_for('index')), the output on the terminal will be; Mad-I Student Data
  2. If #== print statement ==# is replaced by; print(url_for('profile', student_name='John', student_id= 101)), the output on the terminal will be; /student?student_name=John&student_id=101
  3. If #== print statement ==# is replaced by; print(url_for('index')), the output on the terminal will be; /home
  4. If #== print statement ==# is replaced by; print(url_for('profile', student_name='John', student_id=101)), the output on the terminal will be; /student/John/101

Question 18 MSQ · 4.5 marks

Consider the following flask view function defined to add a product and select correct statement(s).

@app.route("/add", methods = ['GET', 'POST'])
def add_product():
    if request.method == 'POST':
        name = request.form.get('name')
        category = request.form.get('category')
        if name == "":
            return redirect('/add')
        if category == "":
            return redirect('/add')
        return f"Product {name} is added in {category} category."
    return """
    <form action="/add" method="post">
        Product Name: <input type="text" name="name" minlength="2"><br>
        Product Category: <input type="text" name="category" required><br>
        <input type="submit" value="Add Product">
    </form>
    """

  1. The form to add the product is statically generated.
  2. The form to add the product is dynamically generated.
  3. The form rendered for /add endpoint has frontend validation.
  4. The form rendered for /add endpoint has backend validation.

Question 3 MCQ · 4.5 marks

Consider the following flask application.

from flask import Flask, abort
app = Flask (__name__)

users = ["admin", "user_1", "user_2", "user_3"]

@app.route('/home/<string:username>', methods = ['POST'])
def home (username):
    if username in users:
        return f"<h1>Hello {username}, Welcome!</h1>"
    else:
        abort (404)

@app.errorhandler(404)
def user_error_1(error):
    return "<h1>The user you are looking for is invalid.</h1>"

@app.errorhandler (405)
def user_error_2(error):
    return "<h1>Please check the web request.</h1>"

app.run()

If the application is running locally on http://127.0.0.1:5000. What will be rendered on the browser for url http://127.0.0.1:5000/home/user_4?

  1. Hello user_4, Welcome!
  2. The user you are looking for is invalid.
  3. Not Found
  4. Please check the web request

Question 5 MSQ · 3 marks

Consider the following flask application. app.py

from flask import Flask, abort
app = Flask (__name__)

@app.route('/<uname>')
def index(uname):
    if uname[0].isdigit():
        abort (400, "Bad Request")
    return '<h1>Good Username</h1>'

app.run(debug=True)

Which of the following statements is/are true if the application is running locally on http://127.0.0.1:5000?

  1. For URL http://127.0.0.1:5000/MAD1?uname=102 the browser will render Bad Request.
  2. For URL http://127.0.0.1:5000/MAD1?uname=102 the browser will render Good Username.
  3. For URL http://127.0.0.1:5000/102?uname=MAD1 the browser will render Bad Request.
  4. For URL http://127.0.0.1:5000/102?uname=MAD1 the browser will render Good Username.

06 Apr 2026

Question 9 MSQ · 2 marks

Which of the following flask routes can take dynamic value in the URL like "/user/55"?

  1. @app.route("/user/id")
  2. @app.route("/user/<int:id>")
  3. @app.route("/user/<id>")
  4. @app.route("/user/<float:id>")

Question 10 MSQ · 2 marks

Consider the following Python Flask code.

from flask import Flask
app=Flask(__name__)

@app.route("/user/<name>")
def greet(name):
    return f"<p>Welcome {name}</p>"

app.run(debug=True)

Assume that the Flask app is running at http://127.0.0.1:5000. Which of the following URL requests will render the output without any errors?

  1. http://127.0.0.1:5000/user/IITM
  2. http://127.0.0.1:5000/user/101
  3. http://127.0.0.1:5000/user/10/greet
  4. http://127.0.0.1:5000/user
  5. http://127.0.0.1:5000/user/BS?id=101

Question 3 MCQ · 3 marks

Consider the following Flask application.

from flask import Flask, request
from string import Template

app = Flask(__name__)

@app.route("/welcome")
def welcome():
    username = request.args.get("user", "Guest")
    role = request.args.get("role", "Member")

    t = Template("Hello $name! Your role is $role_type.")
    result = t.substitute(name=username.upper(), role_type=role.lower())
    return result

if __name__ == "__main__":
    app.run()

Assume that the Flask app is running at http://127.0.0.1:5000. What will be the rendered output in the browser for the URL: http://127.0.0.1:5000/welcome?user=Alice&role=ADMIN

  1. It raises a KeyError because $role_type is missing in the URL.
  2. Hello Guest! Your role is member.
  3. Hello Alice! Your role is ADMIN.
  4. Hello ALICE! Your role is admin.

Question 13 MSQ · 5 marks

Consider the following Python Flask code. Filename: app.py

from flask import Flask, request
app=Flask(__name__)

@app.route("/login",methods=["POST"])
def signin():
    args=request.get_json()
    if args["uid"]=="admin" and args["pwd"]=="12345":
        return "Welcome Admin!"
    else:
        return "Invalid credentials..."

app.run(debug=True)

Assume that the Flask app is running at http://127.0.0.1:5000. Which of the following “curl” commands or URL requests returns Method Not Allowed error(on bash terminal)?

  1. curl -X POST --json '{"uid":"admin","pwd":"xyz"}' http://127.0.0.1:5000/login
  2. curl -X GET --json '{"uid":"admin","pwd":"xyz"}' http://127.0.0.1:5000/login
  3. URL request: http://127.0.0.1:5000/login
  4. curl --json '{"uid":"admin","pwd":"12345"}' http://127.0.0.1:5000/login
  5. curl -X POST --json '{"uid":"admin","pwd":"12345"}' http://127.0.0.1:5000/login

Check your answers →

Weeks covering this topic

Other MAD 1 topics