Question 1
You're designing an API to update a user's profile picture but your database has 4 records in a row, profile picture is one of them. Which HTTP method is most appropriate?
POST
PATCH
PUT
DELETE

The IIT Madras BS Modern Application Development I (MAD 1) End Term paper sat on 31 Aug 2025, in the May 2025 term, set QDD1: 32 questions for 100 marks in 180 minutes. Every question is below with its answer. Take it as a timed mock test to be marked, or read it through first.
You're designing an API to update a user's profile picture but your database has 4 records in a row, profile picture is one of them. Which HTTP method is most appropriate?
POST
PATCH
PUT
DELETE
Correct answer
PATCH
What is the correct sequence of operations when receiving a form in Flask?
Validate → Render → Access → Store
Access → Store → Validate → Render
Access → Validate → Store → Redirect
POST → GET → Redirect → Validate
Correct answer
Access → Validate → Store → Redirect
Consider the following statements and choose the correct option
Statement 1: It is mandatory to implement server-side validations and client-side validations. Statement 2: Server-side validations can be implemented using HTML5.
Statement 1 is false, while statement 2 is true
Statement 1 is true, while statement 2 is false
Both statements are false
Both statements are true
Correct answer
Both statements are false
What will be the output when accessing http://localhost:5000/user/42 in the following Flask app?
from flask import Flaskapp = Flask(__name__)
@app.route('/user/<uid>')def show_user(uid): return f"User ID: {uid * 2}"
app.run(debug=True)Correct answer
Consider the following HTML form:
<form action="/search" method="get"> <input type="text" name="q"> <input type="submit">Search</input></form>What URL will be generated when the user enters "flask" in the input box and clicks on the submit button?
Correct answer
You're creating a registration form. The form is written as:
<form action="/register" method="post">And in Flask:
@app.route("/register")def register(): return "Form received"When the user submits the form, they see a 405 Method Not Allowed error. Why is this happening?
There is no return statement inside the function
The form is missing CSRF protection
The Flask route does not allow POST method
The route should have a trailing slash
Correct answer
The Flask route does not allow POST method
You created the following templates:
base.html
<html><body> {% block content %}{% endblock %}</body></html>home.html
{% extends "base.html" %}<h1>Welcome!</h1>But when rendered, "Welcome!" doesn't appear. Why?
Correct answer
A user downloads a 10 MB file from a server with 5 Mbps speed. How long does it approximately take?
2 seconds
10 seconds
16 seconds
1.6 seconds
Correct answer
16 seconds
Suppose you have these models in your Flask-SQLAlchemy app:
class Author(db.Model): id = db.Column(db.Integer, primary_key=True) books = db.relationship('Book', backref='author', cascade="all, delete")
class Book(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80)) author_id = db.Column(db.Integer, db.ForeignKey('author.id'))If you delete an Author instance from the database, what happens to their related Book instances?
Correct answer
Consider the following HTML code snippet (without any CSS styling).
<div> <p>This is paragraph 1</p> <span>Span element 1</span> <span>Span element 2</span> <p>This is paragraph 2</p> <a href="#">Link 1</a> <a href="#">Link 2</a> <div>Nested div content</div> <strong>Bold text</strong> <em>Italic text</em></div>Which of the following statements correctly describes how the elements will be displayed by default in a browser?
Correct answer
Consider the following HTML document with internal CSS and inline styles.
<!DOCTYPE html><html><head> <style> p { color: blue; font-size: 16px; font-weight: normal; } .highlight { color: red; font-weight: bold; } #special { color: green; font-size: 20px; } p.highlight { color: orange; } </style></head><body> <p class="highlight" id="special" style="color: purple; font-size: 14px;"> Paragraph 5 </p></body></html>What will be the final color and font-size for "Paragraph 5"?
Color: green, Font-size: 20px
Color: orange, Font-size: 14px
Color: purple, Font-size: 20px
Color: purple, Font-size: 14px
Correct answer
Color: purple, Font-size: 14px
1-c, 2-a, 3-d, 4-b
1-d, 2-c, 3-a, 4-b
1-c, 2-d, 3-b, 4-a
1-c, 2-d, 3-a, 4-b
Correct answer
1-c, 2-d, 3-a, 4-b
Consider the following Python code.
File name: main.py
def funA(func): def inner_wrapper(): print("Wrapper function of funA") res1 = func() res2 = func() return res1, res2 return inner_wrapper
@funAdef funB(): return "I am from funB"
print(funB())What will be the output, when running the above code using the command “python main.py”?
Correct answer
Consider the HTML code below, what will be the text color of the paragraph?
<!DOCTYPE html><head> <style> p { color: blue; } p.important { color: red; } #main p.important { color: green; } </style></head><body> <div id="main"> <p class="important">Hello World!</p> </div></body></html>Blue
Red
Green
Black
Correct answer
Green
1-a, 2- c, 3-b, 4-d, 5-e
1-b, 2- c, 3-a, 4-e, 5-d
1-e, 2- d, 3-b, 4-a, 5-c
1-e, 2- d, 3-c, 4-a, 5-b
Correct answer
1-e, 2- d, 3-b, 4-a, 5-c
You are working on a team project hosted on GitHub. After making changes to your local files, you run the following commands in this exact order:
git statusgit add .git commit -m "Fixed header bug"git pushgit pullAssuming your teammate pushed a new change just before you did git push, what is the most likely outcome?
Correct answer
Consider the following Python script that processes command line arguments and uses Jinja2 templates.
python: app.py
import sysfrom jinja2 import Template
pre_message = sys.argv[1] if len(sys.argv) > 1 else ""pre_language = sys.argv[2] if len(sys.argv) > 2 else "unknown"
post_message = pre_message.strip().lower().replace(" ", "_")post_language = pre_language.capitalize()
template_string = """<div> <h1>{{ post_message | upper }}</h1> <p>Message: {{ post_message }}</p> <p>Language: {{ post_language }}</p> <p>Count: {{ pre_message | length }}</p></div>"""
template = Template(template_string)output = template.render( pre_message = pre_message, post_message = post_message, post_language = post_language)
print(output)If the script is run with the command:
bash
python app.py " Hello World " "python"What will be the output for the following template variables?
Correct answer
Consider the following Flask application structure and code.
my_project/├── app.py├── views/│ └── dashboard.html├── templates/│ ├── base.html│ └── home.html└── custom_templates/ ├── admin/ │ └── login.html └── user/ └── profile.htmlapp.py:
from flask import Flask, render_template
app = Flask(__name__, template_folder='custom_templates')
@app.route('/')def home(): return render_template('home.html')
@app.route('/admin')def admin_login(): return render_template('admin/login.html')
@app.route('/profile')def user_profile(): return render_template('user/profile.html')
@app.route('/dashboard')def dashboard(): return render_template('dashboard.html')
if __name__ == '__main__': app.run(debug=True)Which of the following statements about the template rendering behavior is correct?
All routes will work correctly as Flask will automatically search in both templates/ and custom_templates/ folders
The / and /dashboard routes will fail with TemplateNotFound error, while /admin and /profile routes will work correctly
Only the /admin and /profile routes will work correctly, while / and /dashboard routes will fail with TemplateNotFound error
All routes will fail because Flask requires the template folder to be named exactly templates
Correct answer
Only the /admin and /profile routes will work correctly, while / and /dashboard routes will fail with TemplateNotFound error
Examine the following Python code snippet.
File: logger_test.py
import loggingimport sys
logging.basicConfig(level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(message)s')
def process_data(num): logging.debug("Starting data processing") logging.info("Processing number: %d", num)
if num == 0: logging.warning("Zero value detected - potential division by zero") return None elif num < 0: logging.error("Negative number provided: %d", num) return None else: result = 100 / num logging.info("Calculation completed successfully") return result
try: input_num = int(sys.argv[1]) result = process_data(input_num) if result: print(f"Result: {result}")except IndexError: logging.critical("No command line argument provided")except ValueError: logging.error("Invalid input - not a number")What will be the output when running the command: python logger_test.py -5 ?
Correct answer
Which statements about REST API design are correct?
PUT requests should be idempotent
GET requests can have request bodies for complex queries
PATCH is used for partial updates
DELETE must return the deleted resource
Correct answers
PUT requests should be idempotent
PATCH is used for partial updates
Correct answers
Consider the following Python code.
from string import Template
output = "List of courses in IITM BS Diploma : $c1, $c2, $c3, $c4, $c5"my_template = Template(output)print(==Missing code here===)Which of the following statement(s) prints the output without any KeyError exception?
Correct answers
Consider the following Flask app code.
from flask import Flask, requestvalid_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. Select the URL(s) that render Not Found error.
Correct answers
Examine the following Python test file:
Filename: math_tests.py
import pytest
def multiply(a, b): return a * b
def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b
@pytest.mark.unitdef test_multiply_positive(): assert multiply(3, 4) == 12
@pytest.mark.integrationdef test_divide_normal(): assert divide(10, 2) == 5.0
@pytest.mark.slow@pytest.mark.integrationdef test_complex_calculation(): result = divide(multiply(6, 7), 2) assert result == 21.0@pytest.mark.unitdef test_multiply_negative(): assert multiply(-2, 3) == -6Consider the following pytest command output:
========= 1 passed, 3 deselected in 0.02s =========Which of the following pytest commands would produce the output shown above?
Correct answers
Correct answers
Prashant and Nikita are creating a quiz question paper collaboratively. They are each working on different sections — and complete their tasks in parallel. Meanwhile, Mayur is enjoying a single-player game that finishes when the game loop ends.
To compare productivity:
"Team".Prashant and Nikita send their task completion times to a Flask backend via query parameters.The server must simulate parallel execution of their tasks (i.e., max(prashant_time, nikita_time)) and compare it against Mayur's game time. The route returns who finishes faster.
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/task')def task(): prashant_time = int(request.args.get("prashant")) nikita_time = int(request.args.get("nikita", 3)) mayur_time = int(request.args.get("mayur", 6))
team_time = max(prashant_time, nikita_time) # parallel processing winner = "Team" if team_time < mayur_time else "Mayur"
return jsonify({ "winner": winner, "team_time": team_time, "mayur_time": mayur_time })Based on the above data, answer the given subquestions.
Correct answer
Prashant and Nikita are creating a quiz question paper collaboratively. They are each working on different sections — and complete their tasks in parallel. Meanwhile, Mayur is enjoying a single-player game that finishes when the game loop ends.
To compare productivity:
"Team".Prashant and Nikita send their task completion times to a Flask backend via query parameters.The server must simulate parallel execution of their tasks (i.e., max(prashant_time, nikita_time)) and compare it against Mayur's game time. The route returns who finishes faster.
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/task')def task(): prashant_time = int(request.args.get("prashant")) nikita_time = int(request.args.get("nikita", 3)) mayur_time = int(request.args.get("mayur", 6))
team_time = max(prashant_time, nikita_time) # parallel processing winner = "Team" if team_time < mayur_time else "Mayur"
return jsonify({ "winner": winner, "team_time": team_time, "mayur_time": mayur_time })Based on the above data, answer the given subquestions.
Correct answer
Consider the following Flask-SQLAlchemy models for a library management system:
File: models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Library(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), unique=True, nullable=False) location = db.Column(db.String(200), nullable=False) books = db.relationship('Book', backref='library_ref', lazy=True)
class Author(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) email = db.Column(db.String(120), unique=True, nullable=True) books = db.relationship('Book', backref='author_ref', lazy=True)
class Book(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(150), nullable=False) isbn = db.Column(db.String(13), unique=True, nullable=False) library_id = db.Column(db.Integer, db.ForeignKey('library.id'), nullable=False) author_id = db.Column(db.Integer, db.ForeignKey('author.id'), nullable=False) is_available = db.Column(db.Boolean, default=True)File: app.py
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/books/<int:library_id>', methods=['GET'])def get_library_books(library_id): library = Library.query.get_or_404(library_id) available_books = Book.query.filter_by( library_id=library_id, is_available=True ).all()
result = [] for book in available_books: result.append({ 'id': book.id, 'title': book.title, 'author': book.author_ref.name, 'isbn': book.isbn })
return jsonify({ 'library': library.name, 'location': library.location, 'available_books': result })Based on the above data, answer the given subquestions.
Which of the following statements about the database schema and model relationships is correct?
Correct answer
Consider the following Flask-SQLAlchemy models for a library management system:
File: models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Library(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), unique=True, nullable=False) location = db.Column(db.String(200), nullable=False) books = db.relationship('Book', backref='library_ref', lazy=True)
class Author(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) email = db.Column(db.String(120), unique=True, nullable=True) books = db.relationship('Book', backref='author_ref', lazy=True)
class Book(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(150), nullable=False) isbn = db.Column(db.String(13), unique=True, nullable=False) library_id = db.Column(db.Integer, db.ForeignKey('library.id'), nullable=False) author_id = db.Column(db.Integer, db.ForeignKey('author.id'), nullable=False) is_available = db.Column(db.Boolean, default=True)File: app.py
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/books/<int:library_id>', methods=['GET'])def get_library_books(library_id): library = Library.query.get_or_404(library_id) available_books = Book.query.filter_by( library_id=library_id, is_available=True ).all()
result = [] for book in available_books: result.append({ 'id': book.id, 'title': book.title, 'author': book.author_ref.name, 'isbn': book.isbn })
return jsonify({ 'library': library.name, 'location': library.location, 'available_books': result })Based on the above data, answer the given subquestions.
Correct answer
Consider the following flask code and answer the given subquestions.
from flask import Flask, request
app = Flask(__name__)
@app.route('/score')def score(): name = request.args.get('name', 'Guest') try: marks = int(request.args.get('marks', 0)) except ValueError: return f"Invalid marks for {name}"
if marks >= 90: grade = "A" elif marks >= 75: grade = "B" elif marks >= 60: grade = "C" else: grade = "F"
return f"{name} scored {marks} and received grade {grade}"
app.run(debug=True)Alex scored 0 and received grade F
Invalid marks for Alex
Alex scored eighty and received grade F
Error 500: Internal Server Error
Correct answer
Invalid marks for Alex
Consider the following flask code and answer the given subquestions.
from flask import Flask, request
app = Flask(__name__)
@app.route('/score')def score(): name = request.args.get('name', 'Guest') try: marks = int(request.args.get('marks', 0)) except ValueError: return f"Invalid marks for {name}"
if marks >= 90: grade = "A" elif marks >= 75: grade = "B" elif marks >= 60: grade = "C" else: grade = "F"
return f"{name} scored {marks} and received grade {grade}"
app.run(debug=True)Guest scored 88 and received grade A
Guest scored 88 and received grade B
Guest scored 0 and received grade F
Invalid marks for Guest
Correct answer
Guest scored 88 and received grade B
Consider the following flask code and answer the given subquestions.
from flask import Flask, request
app = Flask(__name__)
@app.route('/score')def score(): name = request.args.get('name', 'Guest') try: marks = int(request.args.get('marks', 0)) except ValueError: return f"Invalid marks for {name}"
if marks >= 90: grade = "A" elif marks >= 75: grade = "B" elif marks >= 60: grade = "C" else: grade = "F"
return f"{name} scored {marks} and received grade {grade}"
app.run(debug=True)Anya scored 59.5 and received grade F
Anya scored 0 and received grade F
Invalid marks for Anya
Anya scored 59 and received grade F
Correct answer
Invalid marks for Anya