Home / MAD1 / Week 1 / Real questions
60 questions pulled from past papers whose wording matches this week's topics, newest first, duplicates removed. Pick your answers, then press Check answers. Figures and answer keys are the originals.
If the application is running locally on http://127.0.0.1:5000, select the correct options.```python
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)
```
For the URL: ``` http://127.0.0.1:5000/learn/web/Python?level=advanced ``` The browser will render: **Course not available!**

For the URL: ``` http://127.0.0.1:5000/course/ML/Python?topic=NLP ``` The browser will render: Welcome to Python course!

For the URL: ``` http://127.0.0.1:5000/learn/basics/Python?level=beginner ``` The browser will render: Welcome to Python course!

For the URL: ``` http://127.0.0.1:5000/course/Java/React?type=Framework ``` The browser will render: **Course not available!**

``` curl -X PUT -d "status=active&role=admin" https://api/users/update ```
What will be the response?File name: app.py
```python
from flask_restful import reqparse, Resource, Api
from flask import Flask
parser = reqparse.RequestParser()
parser.add_argument("n", type=int, required=True)
app = Flask(__name__)
api = Api(app)
class MyResponse(Resource):
def post(self):
args = parser.parse_args()
return args
api.add_resource(MyResponse, "/")
app.run(debug=True)
```
Assume that the Flask app is running at http://127.0.0.1:5000. The client sends the below CURL request in the git bash terminal.
```bash
curl -X POST http://127.0.0.1:5000 -H "Content-Type: application/json" -d "{\"n\":3}"
```
The above flask app is running on "http://127.0.0.1:5000". Which of the following commands will return a runtime error?```python
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class UserResource(Resource):
def get(self):
return {"status": "GET request"}, 200
def post(self, user_id):
return {"status": "POST request", "user_id": user_id}, 201
api.add_resource(UserResource, "/users", "/users/<int:user_id>")
if __name__ == "__main__":
app.run(debug=True)
```
``` curl http://127.0.0.1:5000/users/5001 -X GET ```

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

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

``` curl http://127.0.0.1:5000/users -X GET ```
What will be rendered by the browser?File name: home.html
```html
<!DOCTYPE html>
<html lang="en">
<style>
div{color:green}
.cdiv{color:red}
#div1{color:blue}
</style>
<body>
<div id="div1" class="cdiv">IITM BS Degree in Data Science</div>
</body>
</html>
```
IITM BS Degree in Data Science

IITM BS Degree in Data Science

IITM BS Degree in Data Science

1. IITM BS Degree in Data Science
Assume that the Flask app is running at http://127.0.0.1:5000. Based on the above data, answer the given subquestions.
What will be the output when you run the following code in the terminal
and then access in the browser with the following link
?```python
from flask import Flask
import sys
app = Flask(__name__)
MULTIPLIER = int(sys.argv[1]) if len(sys.argv) > 1 else 2
@app.route('/calculate/<int:value>')
def calculate(value):
return f"Result: {value * MULTIPLIER}"
if __name__ == '__main__':
app.run()
```
```
python app.py 7
```
http://localhost:5000/calculate/6
```python
from flask import Flask, request
app = Flask(__name__)
@app.route("/total")
def total():
price = request.args.get("price", 0)
qty = request.args.get("qty", 1)
result = price * qty
return str(result)
app.run()
```
Assume that the above Flask app is running at http://127.0.0.1:5000. What will be rendered for the URL request http://127.0.0.1:5000/total?price=5&qty=2?
```python
from flask import Flask
app = Flask(__name__)
@app.route("/user/<name>")
def user(name):
return f"User: {name}"
@app.route("/user/admin")
def admin():
return "Admin Panel"
app.run()
```
Assume that the Flask app is running at http://127.0.0.1:5000. What response is returned when http://127.0.0.1:5000/user/admin is accessed?
File name: app.py
```python
from flask import Flask
app = Flask(__name__)
@app.route("/calculate/<int:v1>/<int:v2>")
def compute(v1, v2):
try:
return f"{v1 / v2}"
except:
return "Arithmetic operation error!"
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 return **Not Found** ?
``` http://127.0.0.1:5000/calculate/10/5 ```

``` http://127.0.0.1:5000/calculate/3/0.2 ```

``` http://127.0.0.1:5000/calculate/3/2?v1=1 ```

``` http://127.0.0.1:5000/calculate?v1=5&v2=2 ```

| Column A | Column B | |---|---| | 1. ftp | A. Web domain | | 2. 127.0.0.1 | B. Protocol | | 3. `<b></b>` | C. Decorator | | 4. seek.onlinedegree.iitm.ac.in | D. Loop back IP | | 5. @app.route | E. HTML element |
Which of the following options are true?File name: app.py
```python
from flask import Flask, url_for
app = Flask(__name__)
@app.route("/home")
def index():
return "Home page!"
@app.route("/login")
def signin():
return "Login page!"
@app.route("/<route>")
def get_url(route):
return url_for(route, _external=True)
app.run(debug=True)
```
Assume that the Flask app is running at http://127.0.0.1:5000.
File name: app.py
```python
from flask import Flask
app = Flask(__name__)
@app.route("/calculate/<v1>/<v2>")
def compute(v1, v2):
try:
return f"{int(v1) / int(v2)}"
except:
return "Arithmetic operation error!"
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 return "Arithmetic operation error!"?
``` http://127.0.0.1:5000/calculate/4/"2" ```

http://127.0.0.1:5000/calculate/4/4

``` http://127.0.0.1:5000/calculate/4/0.2 ```

``` http://127.0.0.1:5000/calculate/4/2?v1=1 ```

``` http://127.0.0.1:5000/calculate/4.0/0.5 ```
Which of the following statements correctly describes how the elements will be displayed by default in a browser?```html <div> <h1>Content 1</h1> <p>Content 2</p> <span>Content 3</span> <span>Content 4</span> </div> ```
,
and
tags will start on new lines as they are block elements.`<h1/>` `<p>` ```html <span> ```
and
tags will start on new lines, others will display inline.`<h1/>` `<p>`
tags will start on new lines, others will display inline.```html <span> ```

``` curl -X POST -d "email=user@test.com&password=secret" https://auth/signin ```
Based on the above data, answer the given subquestions.

Assume that the Flask app is running at http://127.0.0.1:5000. The client sends the below CURL request in the git bash terminal.
What will be the response?File name: app.py
```python
from flask_restful import reqparse, Resource, Api
from flask import Flask
parser = reqparse.RequestParser()
parser.add_argument("n", type=int, required=True)
app = Flask(__name__)
api = Api(app)
class MyResponse(Resource):
def post(self):
args = parser.parse_args()
return args
api.add_resource(MyResponse, "/")
app.run(debug=True)
```
```
curl -X POST http://127.0.0.1:5000 -H "Content-Type: application/json" -d '{}'
```
Assume that the Flask app is running at
. What will be rendered for the URL request
?File name: base.html
```html
<!DOCTYPE html>
<html lang="en">
<body>
{% block content %}
<div>Parent content</div>
{% endblock %}
</body>
</html>
```
File name: child.html
```html
{% extends "base.html" %}
{% block content %}
<div>Child content</div>
{% endblock %}
```
File name: app.py
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/home")
def index():
return render_template("child.html")
app.run(debug=True)
```
http://127.0.0.1:5000
http://127.0.0.1:5000/home
File name: app.py
```python
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
full_name = db.Column(db.String, unique=True)
class UserPosts(db.Model):
__tablename__ = "user_posts"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String, unique=True, nullable=False)
description = db.Column(db.String, nullable=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
class UserApi(Resource):
def post(self):
user_data = request.json
==Missing code 1==
db.session.add(user)
db.session.commit()
return {"msg": "User added!"}, 201
class UserPostsApi(Resource):
def post(self):
post_data = request.json
==Missing code 2==
db.session.add(user_post)
db.session.commit()
return {"msg": "Post added!"}, 201
```
Which of the following is the most suitable ==Missing code 1== and ==Missing code 2==? So that the Flask application does not return any run-time error?
==Missing code 1==
```python
user = User(full_name=user_data["full_name"])
```
==Missing code 2==
```python
user_post = UserPosts(
title=post_data["title"],
description=post_data["description"],
user_id=post_data["user_id"],
)
```
```python
==Missing code 1==
user = User(name=user_data["full_name"])
==Missing code 2==
user_post = UserPosts(
post_title=post_data["title"],
post_description=post_data["description"],
post_user_id=post_data["user_id"],
)
```
```python
==Missing code 1==
user_data = User(full_name=user_data["full_name"])
==Missing code 2==
user_post_data = UserPosts(
title=post_data["title"],
description=post_data["description"],
user_id=post_data["user_id"],
)
```
```
==Missing code 1==
user_data = User(name=user_data["full_name"])
==Missing code 2==
user_post_data = UserPosts(
post_title=post_data["title"],
post_description=post_data["description"],
post_user_id=post_data["user_id"],
)
```
```python
import sys
from flask import Flask, render_template
app = Flask(__name__, static_folder = 'public')
@app.route('/')
def func():
folder_1 = sys.argv[1]
folder_2 = sys.argv[2]
if app.static_folder == folder_1:
return f"<h1>Static folder verified: {folder_1}</h1>"
if app.static_folder == folder_2:
return f"<h1>Static folder verified: {folder_2}</h1>"
return "<h1>Invalid argument</h1>"
app.run(debug = True)
```
If the application is running locally on http://127.0.0.1:5000. What will be rendered by the browser for the command:
```
python app.py /assets /public
```
allows code to be tested without a server, which of the following statements is correct?

```
test_request_context()
```
```python
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/api')
def api():
return 'API Response'
@app.route('/data/<category>')
def data(category):
return f'Data for {category}'
with app.test_request_context():
#== print statement ==#
```
is replaced by
, the output on the terminal will be 
```python
#=== print statement ===#
```
```python
print(url_for('data', category='sales'))
```
```
/data?category=sales
```
is replaced by
, the output on the terminal will be 
```python
#=== print statement ===#
```
```python
print(url_for('data', category='sales', format='json'))
```
```
/data/sales/json
```
is replaced by
, the output on the terminal will be 
```python
#=== print statement ===#
```
```python
print(url_for('api', category='sales'))
```
```
/api?category=sales
```
is replaced by
, the output on the terminal will be 
```python
#=== print statement ===#
```
```python
print(url_for('api'))
```
/api

```python
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
It raises a KeyError because `$role_type` is missing in the URL.

```python
@app.route("/user/id")
```
```python
@app.route("/user/<int:id>")
```
```python
@app.route("/user/<id>")
```
```python
@app.route("/user/<float:id>")
```

```python
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?

Filename: app.py
```python
from flask import Flask, render_template
app=Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
app.run(debug=True)
```
Filename: index.html
```html
<!DOCTYPE html>
<html lang="en">
<body>
<div>
Output is:
{% for i in [1,2,3] %}
{% set x = i %}
{% endfor %}
{{ x }}
</div>
</body>
</html>
```
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?
What will be the output in the console window when the above HTML doc is rendered on the browser ?```html
<!DOCTYPE html>
<html>
<body>
<ol id="lst">
<li>App Dev-1</li>
</ol>
</body>
<script>
let lst_items=document.getElementsByTagName("li");
document.getElementById("lst").innerHTML += "<li>App Dev-2</li><li>App dev projects</li>";
console.log(lst_items.length);
</script>
</html>
```
Filename: app.py
```python
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)?

```python
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
products = [
{"id": 1, "name": "books", "price": 56},
{"id": 2, "name": "pens", "price": 61},
{"id": 3, "name": "bulbs", "price": 76},
]
class MyApiResource(Resource):
### Missing code ###
api.add_resource(MyApiResource, "/<int:id>")
if __name__ == "__main__":
app.run(debug=True)
```
Assume that the Flask app is running at http://127.0.0.1:5000. Which of the following codes when placed at ###Missing code ### will work correctly to search a product by id?
```python
def post(self):
for p in products:
if p["id"] == id:
return f"{p['id']}, {p['name']}, {p['price']}"
return f"msg: {id} not found"
```
```python
def get(self,id):
for p in products:
if p["id"] == id:
return f"{p['id']}}, {p['name']}}, {p['price']}}"
return f"msg: {id} not found"
```
```python
def get(self):
for p in products:
if p["id"] == id:
return f"{p['id']}, {p['name']}, {p['price']}"
return f"msg: {id} not found"
```
```python
def post(self, id):
for p in products:
if p["id"] == id:
return f"{p['id']}, {p['name']}, {p['price']}"
return f"msg: {id} not found"
```
Select the option which correctly matches the URL in column A with the rendered output in column B, if the application is running locally on http://127.0.0.1:5000.

```python
from flask import Flask, request
app = Flask(__name__)
@app.route('/calculate')
def calculate():
a = request.args.get('a')
b = request.args.get('b', 2)
c = request.args.get('c', "5")
try:
a = int(a)
b = int(b)
c = int(c)
except:
return "Invalid Input"
if a + b == c:
return f"Sum: {a+b}"
elif a * c == b:
return f"Product: {a*b}"
else:
return f"No match: {a+b+c}"
app.run(debug=True)
```
| URL | Output |
|---|---|
| 1. http://127.0.0.1:5000/calculate?a=3 | a. Sum: 6 |
| 2. http://127.0.0.1:5000/calculate?a=3&d=5 | b. Invalid Input |
| 3. http://127.0.0.1:5000/calculate?a=1&b=5 | c. Sum: 5 |
| 4. http://127.0.0.1:5000/calculate?a=1&b=5&c=6 | d. Product: 5 |
You are running a Flask web application locally using the command: python app.py. On which URL will the application be accessible in the browser?```python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def port():
return "This is the same port question. Yet again, for a reason."
if __name__ == "__main__":
app.run(port=0007)
```

File name: home.html
```html
<body>
{% if user == "admin" %}
<p>Welcome Admin</p>
{% else %}
<p>Welcome User</p>
{% endif %}
</body>
```
File name: app.py
```python
from flask import Flask,render_template
app = Flask(__name__)
@app.route("/")
def login():
return render_template("home.html",user="admin iitm")
app.run(debug=True)
```
Assume that the above code is running on http://127.0.0.1:5000. What will be the rendered output for the URL request http://127.0.0.1:5000 ?

Consider the following Flask application running on http://127.0.0.1:5000.
```python
from flask import Flask
app = Flask(__name__)
@app.route('/profile/<string:username>')
def profile(username):
return f"Profile of {username}"
@app.route('/post/<int:post_id>')
def post(post_id):
return f"Post ID: {post_id}"
app.run(debug=True)
```
What will happen when accessing http://127.0.0.1:5000/post/abc123 ?
``` curl -i <URL> ```

``` curl -v <URL> ```

``` curl --headers <URL> ```

``` curl -X GET <URL> ```
If the flask app is running locally on http://127.0.0.1:5000. What will be the output on the browser for the base URL?app.py
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template("index.html", items=['DaShBoard', 'SETtings',
'HELP'])
app.run()
```
index.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Menu</title>
</head>
<body>
{% macro nav_list(elements) %}
<ol>
{% for element in elements %}
<li><a href="/{{ element|lower }}">{{ element|upper }}</a></li>
{% endfor %}
</ol>
{% endmacro %}
{{ nav_list(items) }}
</body>
</html>
```
1. DaSHBoard 2. SETtings 3. HELP

1. dashboard 2. settings 3. help

1. DASHBOARD 2. SETTINGS 3. HELP

1. DASHBOARD 2. SETTINGS 3. HELP
Based on the above data, answer the given subquestions.

Based on the above data, answer the given subquestions.


HELLO USER

HELLO USER

WELCOME USER

WELCOME USER

Match the type of update with the correct analogy/description: | Update Type | Analogy/Description | | :---------------------- | :----------------------------------------------------------------------- | | 1. Synchronous Updates | A. Runs tasks one after another, without parallel execution | | 2. Asynchronous Updates | B. Freezes the UI until the operation is complete | | 3. Blocking Execution | C. Ordering food at a restaurant and waiting in line until it is ready | | 4. Non-blocking Execution | D. Ordering food, receiving a buzzer, and waiting at a table until it rings | | | E. Allows other tasks to continue while waiting for a response |

Given the following test code:
```python
def test_about(client):
response = client.get('/about')
assert response.status_code == 200
assert b'This is the about page.' in response.data
```
Assume the client fixture works correctly and you are testing a Flask route `/about` that should return the text "This is the about page.". Which of the following options would cause this test to fail?
The route `/about` is missing in `app.py`.

The route `/about` exists but returns "About us page" instead.

The route `/about` returns `<p>this is the about page.</p>` instead of plain text.
The Requests table represents service bookings made by customers. Based on the above data, answer the given subquestions.


```sql SELECT c.name, s.service_name FROM customers c, services s WHERE c.id = s.id; ```

```sql SELECT c.name, r.status FROM customers c JOIN services s ON c.id = s.id; ```

```sql SELECT c.name, s.service_name FROM customers c JOIN requests r ON c.id = r.customer_id JOIN services s ON r.service_id = s.id; ```

```sql SELECT c.name, s.service_name FROM services s LEFT JOIN customers c ON s.id = c.id; ```
The Requests table represents service bookings made by customers. Based on the above data, answer the given subquestions.


```sql SELECT r.customer_id, COUNT(*) AS total_requests FROM requests r; ```

```sql SELECT c.name, COUNT(r.service_id) AS total_requests FROM customers c JOIN requests r ON c.id = r.customer_id GROUP BY c.name; ```

```sql SELECT c.name, COUNT(s.id) AS total_requests FROM customers c JOIN services s ON c.id = s.id GROUP BY c.name; ```

```sql SELECT c.name, r.service_id FROM customers c JOIN requests r ON c.id = r.customer_id; ```
The Requests table represents service bookings made by customers. Based on the above data, answer the given subquestions.


```python customer = Customer.query.filter_by(id=1).first() services = Service.query.all() ```

```python services = Service.query.filter_by(customer_id=1).all() ```

```python customer = Customer.query.get(1) services = [r.service for r in customer.requests] ```

```python services = Request.query.filter_by(id=1).all() ```

``` curl -X POST -d "username=student&password=1234" https://student/login ```

Consider the following HTML5 form:
```html
<form method="POST" action="/submit">
<input type="email" name="email" required>
<input type="password" name="password" required minlength="8">
<input type="number" name="age" min="18" max="65" required>
<button type="submit">Submit</button>
</form>
```
Which of the following attributes are HTML5 native validation features that work without JavaScript?
Consider the following Flask-RESTful code:
```python
class UserResource(Resource):
def get(self, user_id=None):
if user_id:
return {"message": "User details", "id": user_id}, 200
return {"message": "All users"}, 200
def post(self):
return {"message": "User created"}, 201
api.add_resource(UserResource, '/users', '/users/<int:user_id>')
```
Which of the following requests will execute successfully?
In a Flask-Login protected route below:
```python
@app.route('/dashboard')
@login_required
def dashboard():
return f"Welcome {current_user.username}"
```
What happens when an unauthenticated user tries to access /dashboard?
Consider the following code:
app.py
```python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def port():
return "This is the port question."
if __name__ == "__main__":
app.run(port=5008)
```
You are running a Flask web application locally using the command: python app.py. On which URL will the application be accessible on the browser?
http://127.0.0.1:5000/

http://localhost:0000/

http://0.0.0.0:5000/

http://localhost:5008/

Which of the following Flask view functions will return a 404 error for the URL: ``` http://127.0.0.1:5000/profile/user123/active/2024? ```

```python
@app.route('/profile/<username>/<status>/<int:year>')
def profile(username, status, year):
info = {'username': username, 'status': status, 'year': year}
return info
```
```python
@app.route('/profile/<string:username>/<string:status>/<string:year>')
def profile(username, status, year):
info = {'username': username, 'status': status, 'year': year}
return info
```
```python
@app.route('/profile/<username>/<status>/<year>')
def profile(username, status, year):
info = {'username': username, 'status': status, 'year': year}
return info
```
```python
@app.route('/profile/user/<username>/<status>/<year>')
def profile(username, status, year):
info = {'username': username, 'status': status, 'year': year}
return info
```