Home / Past papers / MAD1 End Term / this paper

You executed the following: ```python student = Student.query.filter_by(id=2).first() student.name = "Riya" db.session.add(student) print(student.name) ``` What will this print?

You define two routes in your Flask app as:
```python
@app.route('/home')
def home():
return "Home No Slash"
@app.route('/about/')
def about():
return "About With Slash"
```
A user visits /about (without the trailing slash). What will Flask do?
Responds with 404 Not Found

Automatically redirects to /about/

Responds with "About With Slash"

Responds with "Home No Slash"

Consider the following git branches for a remote repository. ``` feature1 * feature2 main ``` Choose the correct git command sequence to merge *feature1* and *feature2* into the *main* branch.

``` git merge feature1 git merge feature2 git merge main ```

``` git checkout feature1 git merge feature2 git merge main ```

``` git checkout main git merge feature1 git merge feature2 ```

``` git merge main git merge feature1 git merge feature3 ```

Consider the following HTML code.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home page</title>
<style>
/* Missing CSS code */
</style>
</head>
<body>
<div id="mybox">
IITM Online Degree
</div>
</body>
</html>
```
Which of the following /* Missing CSS code */ renders the below output?
A rectangular box with an orange background and a thin dark border, containing the text "IITM Online Degree" in a dark, bold font.
```css
#mybox{
width: 140px;
height: 40px;
background-color: orange;
stroke: black;
}
```
```css
#mybox{
width: 140px;
height: 40px;
background-color: orange;
border-colour: 1px solid black;
}
```
```css
#mybox{
width: 140px;
height: 40px;
background-color: orange;
foreground-color: black;
}
```
```css
#mybox{
width: 140px;
height: 40px;
background-color: orange;
border:1px solid black;
}
```
What will be displayed when running `python app.py 8080` for the following script?
app.py
```python
import sys
port = int(sys.argv[1]) if len(sys.argv) > 1 else 5000
print(f"Server running on port {port}")
```
Error: sys has no attribute argv

Server running on port 8080

Server running on port 5000

``` IndexError on sys.argv[1] ```

Consider the following Flask code.
```python
from flask import Flask
import sys
app = Flask(__name__)
# Read multiplier from command-line
MULTIPLIER = int(sys.argv[1]) if len(sys.argv) > 1 else 1
@app.route('/multiply/<int:number>')
def multiply(number):
return f"Result: {number % MULTIPLIER}"
if __name__ == '__main__':
app.run()
```
What will be the output when you run the following code in the terminal
python app.py 5 and then access in the browser with the following link
http://localhost:5000/multiply/4 ?
Consider the following Python code
File name: main_test.py
```python
import pytest
class TestGroup:
def do_something(self, x, y):
return x % y
def test_one(self):
assert self.do_something(10, 5) == 0, " Is 5 factor of 10? "
def test_two(self):
assert self.do_something(32, 5) == 0, " Is 5 factor of 32 "
```
What will be the output of running the above python script using command line "pytest -v main_test.py"?
``` ==================== short test summary info ==================== FAILED test6.py::TestGroup::test_two - AssertionError: Is 5 factor of 32 ========== 1 failed, 1 passed in 0.12s ========================== ```

```text ==================== short test summary info ==================== test6.py::TestGroup::test_one PASSED [ 50%] test6.py::TestGroup::test_two PASSED [100%] ==================== 2 passed in 0.02s==================== ```

```text ==================== short test summary info ==================== test6.py::TestGroup::test_one FAILED [ 50%] test6.py::TestGroup::test_two FAILED [100%] ==================== 2 failed in 0.02s==================== ```

``` ==================== short test summary info ==================== FAILED test6.py::TestGroup::test_two - AssertionError: Is 5 factor of 10 FAILED test6.py::TestGroup::test_two - AssertionError: Is 5 factor of 32 ==================== 2 failed in 0.12s ==================== ```

You created the following templates:
**base.html**
```html
<html>
<body>
{% block content %}{% endblock %}
</body>
</html>
```
**home.html**
```html
{% extends "base.html" %}
<h1>Welcome!</h1>
```
But when rendered, "Welcome!" doesn't appear. Why?
extends is incorrectly used

base.html has syntax errors

Flask template folder is missing

```html
<h1> should be inside {% block content %}
```
Suppose you have these models in your Flask-SQLAlchemy app:
```python
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?
The books remain in the database, with author_id set to NULL

The books remain, but are marked as "inactive"

The books are also deleted from the database

An error is raised and the deletion is prevented

Consider the following HTML code snippet (without any CSS styling).
```html
<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?
All elements will appear on the same line since they are nested within a single `<div>`

<p>, <div>, and both <a> elements will start on new lines, while <span>, <strong>, and <em> will flow inline with adjacent content

Only `<div>` elements will start on new lines, all other elements will display inline

`<p>` and `<div>` elements will start on new lines, while `<span>`, `<a>`, `<strong>`, and `<em>` elements will flow inline with adjacent inline elements

Consider the following Python code.
File name: main.py
```python
def funA(func):
def inner_wrapper():
print("Wrapper function of funA")
res1 = func()
res2 = func()
return res1, res2
return inner_wrapper
@funA
def funB():
return "I am from funB"
print(funB())
```
What will be the output, when running the above code using the command "python main.py"?
```
('I am from funB', 'I am from funB')
Wrapper function of funA
```
Wrapper function of funA I am from funB I am from funB

```
Wrapper function of funA
('I am from funB', 'I am from funB')
```
```text I am from funB I am from funB Wrapper function of funA ```

Consider the table and match each type of software testing with its correct focus area. | Test Type | Focus Area | |---|---| | 1. Unit Testing | a. Simulated end-user browser-based interaction | | 2. Integration Testing | b. Whole app in full environment including server | | 3. System Testing | c. Real-world verification by actual users before release | | 4. System Testing Automation | d. Multiple components/modules working together | | 5. User Acceptance Testing | e. Smallest logical units (functions/methods) |

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: ```shell git status git add . git commit -m "Fixed header bug" git push git pull ``` Assuming your teammate pushed a new change **just before** you did `git push`, what is the most likely outcome?

Your commit will be rejected because the remote branch is ahead of your local branch.

The `git pull` should have been run **before** `git push` to avoid possible conflicts.

The `git push` will automatically merge your changes with the remote and succeed.

The `git status` will show the conflict before `git push` is run.

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.html
```
**app.py:**
```python
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

Only the /admin and /profile routes will work correctly, while / and /dashboard routes will fail with TemplateNotFound error

The / and /dashboard routes will fail with TemplateNotFound error, while /admin and /profile routes will work correctly

All routes will fail because Flask requires the template folder to be named exactly templates

Examine the following Python code snippet.
File: logger_test.py
```python
import logging
import 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 ?
``` 2024-07-29 10:15:32,123 - DEBUG - Starting data processing 2024-07-29 10:15:32,124 - INFO - Processing number: -5 2024-07-29 10:15:32,125 - ERROR - Negative number provided: -5 ```

``` 2024-07-29 10:15:32,124 - WARNING - Zero value detected - potential division by zero 2024-07-29 10:15:32,125 - ERROR - Negative number provided: -5 ```

``` 2024-07-29 10:15:32,125 - ERROR - Negative number provided: -5 ```

``` 2024-07-29 10:15:32,124 - INFO - Processing number: -5 2024-07-29 10:15:32,125 - ERROR - Negative number provided: -5 2024-07-29 10:15:32,126 - INFO - Calculation completed successfully ```

Consider the following Python code snippet:
**python: app.py**
```python
from string import Template
from jinja2 import Template as JinjaTemplate
import sys
mode = sys.argv[1]
data = {"user": "Bob", "language": "JavaScript", "project": "web app",
"status": "completed"}
template_str = "Hello ${user}! Your {{project}} written in {{language}} is ${status}."
if mode == "hybrid":
str_template = Template(template_str)
intermediate = str_template.substitute(data)
jinja_template = JinjaTemplate(intermediate)
result = jinja_template.render(data)
print(result)
else:
jinja_template = JinjaTemplate(template_str)
result = jinja_template.render(data)
print(result)
```
What will be printed on the terminal for the command: `python app.py hybrid` ?
```
Hello ${user}! Your {{project}} written in {{language}} is
${status}.
```
```
Hello Bob! Your {{project}} written in {{language}} is completed.
```
Hello Bob! Your web app written in JavaScript is completed.

```
Hello ${user}! Your web app written in JavaScript is ${status}.
```
Consider the following Flask app code.
```python
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class MyApiResource(Resource):
def get(self):
return {"response": "GET"}, 200
def post(self, value):
return {"response": "POST", "value": value}, 200
api.add_resource(MyApiResource, "/", "/<int:value>")
if __name__ == "__main__":
app.run(debug=True)
```
The above flask app is running on "http://127.0.0.1:5000". Which of the following commands will return a runtime error?
``` curl http://127.0.0.1:5000/1025 -X GET ```

``` curl http://127.0.0.1:5000/1025 -X POST ```

``` curl http://127.0.0.1:5000/ -X POST ```

``` curl http://127.0.0.1:5000/ -x GET ```

Which of these are true about unit tests in Flask using pytest?

Tests must start with test_ prefix

You must import `FlaskClient` from `flask.testing`

You cannot test routes using `client.get()`

Fixtures help simulate isolated environments

Examine the following Python test file:
Filename: math_tests.py
```python
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.unit
def test_multiply_positive():
assert multiply(3, 4) == 12
@pytest.mark.integration
def test_divide_normal():
assert divide(10, 2) == 5.0
@pytest.mark.slow
@pytest.mark.integration
def test_complex_calculation():
result = divide(multiply(6, 7), 2)
assert result == 21.0
@pytest.mark.unit
def test_multiply_negative():
assert multiply(-2, 3) == -6
```
Consider the following pytest command output:
========= 1 passed, 3 deselected in 0.02s =========
Which of the following pytest commands would produce the output shown above?
``` pytest math_tests.py -m unit ```

``` pytest math_tests.py -m integration ```

``` pytest math_tests.py -m "not sLow" ```

``` pytest math_tests.py -m "slow and integration" ```

None of these

Consider the following HTML code.
**File name: home.html**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home page</title>
<script>
//Missing JS code
</script>
</head>
<body>
<form>
Your name : <input type="text" id="txt1" value="Welcome to IITM Online BS Degree" size="35">
<br>
<input type="button" onclick="doSomething()" value="Click me!">
</form>
</body>
</html>
```
Assume the user clicks the “**Click me!**” button on the below-rendered output.
Your name : [text input field with value "Welcome to IITM Online BS Degree"]
[button with text "Click me!"]
Which of the following //Missing JS code will change the text box font style into **bold**?
```javascript
function doSomething(){
txt1=document.getElementById("txt1");
txt1.style="bold";
}
```
```javascript
function doSomething(){
document.getElementById("txt1").style="bold";
}
```
```javascript
function doSomething(){
txt1=document.getElementById("txt1");
txt1.style.fontWeight="bold";
}
```
```javascript
function doSomething(){
document.getElementById("txt1").style.fontWeight="bold";
}
```

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

URL http://127.0.0.1:5000/course?id=IT2002 will render: ```html <h2>Database Systems - Level: Beginner</h2> ```

URL http://127.0.0.1:5000/course will render: ```html <h2> - Level: Beginner</h2> ```

URL http://127.0.0.1:5000/course?id=IT2005&level=advanced will return HTTP 404 error with message: "Not Found: Course does not exist"

URL http://127.0.0.1:5000/search?q=data&min=2 will render: ```html <ul><li>Database Systems</li><li>Data Structures</li></ul> ```

URL http://127.0.0.1:5000/search?q=web will return HTTP 422 error with message: "Unprocessable Entity: Query too short"

http://127.0.0.1:5000/search?q= will return: ```html <p>No courses found</p> ```

http://127.0.0.1:5000/search?q=system&min=10 will return: HTTP 422 error with message "Unprocessable Entity: Query too short"

http://127.0.0.1:5000/search?q=DATA&min=4 will return: ```html <ul><li>Database Systems</li><li>Data Structures</li></ul> ```

http://127.0.0.1:5000/search?q=python&min=0 will return: ```html <p>No courses found</p> ```

http://127.0.0.1:5000/search?min=2 will return: HTTP 422 error with message "Unprocessable Entity: Query too short"


The given Flask-RESTful app is running on http://127.0.0.1:5000. Which of the following HTTP requests will result in a runtime error due to method signature mismatch?

``` curl http://127.0.0.1:5000/students/123 -X PUT ```

``` curl http://127.0.0.1:5000/students -X POST -d "name=Jay&age=20" ```

``` curl http://127.0.0.1:5000/courses/CS101 -X POST ```

``` curl http://127.0.0.1:5000/students -X DELETE ```

Consider the following HTTP requests to the same Flask-RESTful application. What will be the response status code for each request? Request 1: `curl http://127.0.0.1:5000/students -X POST -d "name=Ashish"` Request 2: `curl http://127.0.0.1:5000/courses/CS101/enroll/456 -X POST` Request 3: `curl http://127.0.0.1:5000/students/789 -X DELETE`


What will be the output of visiting the URL http://localhost:5000/score?name=Alex&marks=eighty ?

What will be the output of visiting the URL http://localhost:5000/score?marks=88 ?

What is the output of visiting the URL http://localhost:5000/score?name=Anya&marks=59.5 ?
Auto-generated summary from the source site. Handy as a checklist; the lessons above explain each idea from scratch.
Here’s a structured summary of the core topics, concepts, principles, and equations essential for the "Modern Application Development I" exam, along with Mermaid knowledge graphs to visualize relationships.
Routing & Views
@app.route() decorator for defining endpoints./<int:id>)./about vs /about/).GET, POST, PUT, DELETE).Key Code Snippets:
@app.route('/user/<int:user_id>')
def show_user(user_id):
return f"User ID: {user_id}"Request Handling
request.args).request.form).request.json).Example:
name = request.args.get('name', default='Guest')Templates (Jinja2)
{% extends %}, {% block %}).{{ variable }}).{% if %}).Example:
{% extends "base.html" %}
{% block content %}
<h1>{{ title }}</h1>
{% endblock %}Error Handling
abort() for HTTP errors (e.g., 404, 400).@app.errorhandler).Example:
abort(404, description="Resource not found")Flask-RESTful
api.add_resource()).reqparse.RequestParser).Example:
parser = reqparse.RequestParser()
parser.add_argument('name', required=True)Database Integration (SQLAlchemy)
db.Model, db.Column, db.relationship).filter_by, first, all).cascade="all, delete").lazy='dynamic' returns a query object).Example:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
posts = db.relationship('Post', lazy='dynamic')Flask-SQLAlchemy Relationships
db.ForeignKey).backref).Example:
class Post(db.Model):
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))HTML/CSS
<div> vs <span>).border, font-weight, background-color).Example:
#mybox {
border: 1px solid black;
background-color: orange;
}JavaScript
document.getElementById).onclick).Example:
function doSomething() {
document.getElementById("txt1").style.fontWeight = "bold";
}Basic Commands
git add, git commit, git push, git pull.git branch, git checkout, git merge).Example Workflow:
git checkout main
git merge feature-branchConflict Resolution
pull before push to avoid conflicts.Unit Testing (pytest)
test_.assert).Example:
def test_addition():
assert add(2, 3) == 5Markers & Selective Testing
@pytest.mark.unit, @pytest.mark.integration.Running specific tests:
pytest -m "unit and not slow"Flask Testing
Flask.test_client() for route testing.Example:
def test_home_page(client):
response = client.get('/')
assert response.status_code == 200HTTP Methods
GET (idempotent, data in URL).POST (data in body, not cached).GET for sensitive data? URLs are logged in browser history.Status Codes
200 OK, 201 Created, 400 Bad Request, 404 Not Found, 422 Unprocessable Entity.RESTful Design
/students/<id>).Bandwidth Calculations
Formula:
Time (seconds) = File Size (MB) × 8 / Speed (Mbps)10 × 8 / 5 = 16 seconds.Nielsen’s Heuristics
Python Logging Levels
DEBUG (10), INFO (20), WARNING (30), ERROR (40), CRITICAL (50).Example:
logging.basicConfig(level=logging.WARNING)
logging.error("This will appear")
logging.info("This will NOT appear")| Concept | Equation | Example |
|---|---|---|
| Bandwidth Time Calculation | Time = (File Size × 8) / Speed | 10 MB at 5 Mbps → 16 seconds |
| Modulo Operation | a % b | 4 % 5 = 4 |
| Grade Calculation | if marks >= 90: grade = "A" | 88 → "B" |
Flask:
lazy='dynamic' returns a query object, not loaded data./about → /about/).request.args is for GET; request.form is for POST.Git:
pull before push to avoid conflicts.git checkout main; git merge feature-branch.Testing:
test_.-m to run marked tests (e.g., pytest -m unit).HTTP:
GET exposes data in URLs; avoid for sensitive data.422 = Unprocessable Entity (validation errors).Frontend:
<div> is block-level; <span> is inline.style.fontWeight = "bold" (not style="bold").Performance:
Logging:
logging.basicConfig(level=logging.WARNING) hides INFO/DEBUG.Jinja2:
{% block %}.{% block %}.lazy='dynamic' with eager loading.GET for passwords (exposed in URLs).@pytest.mark.unit).