Home / Past papers / MAD1 Quiz 1 / this paper

```
{{ courses | len }}
```
```jinja
{{ courses | length }}
```
```html
{{ len(courses) }}
```
None of these

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/

Consider the following statements and select the correct option. Statement 1: The `<span>` elements will start on new lines, while the `<div>` elements will appear inline with surrounding content. Statement 2: The `<p>` and `<div>` elements will each start on new lines and take up the full width of their container, while `<span>`, `<strong>`, and `<em>` will flow inline with surrounding content.

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
```
Consider two Python files, main.py and utils.py with the following code snippets.
File1: main.py
```python
import sys
import utils
print('Processing: ' + sys.argv[2])
```
File2: utils.py
```python
import sys
print('Module: ' + sys.argv[0])
```
What is the output of the following command "python main.py data.txt output.txt" when run on terminal?
``` Module: utils.py Processing: data.txt ```

``` Processing: data.txt Module: utils.py ```

``` Module: main.py Processing: output.txt ```

``` Processing: output.txt Module: main.py ```

Match the following web development concepts with their correct descriptions: | Column A | Column B | |---|---| | 1. PyHTML | A. Lightweight engine in Python for embedding variables inside strings using `$variable` style | | 2. Jinja2 | B. A Python library to build HTML structures programmatically using Python functions | | 3. Template Rendering | C. The process of generating dynamic HTML by combining templates with data | | 4. String Template Rendering | D. Templating engine used by Flask that supports control structures, filters, and inheritance |

Consider the following Python code snippet.
```python
from jinja2 import Template as JTemplate
from string import Template as STemplate
data = {'name1': 'Alice', 'name2': 'name1',
'age1': '25', 'age2': 'age1',
'job1': 'Engineer', 'job2': 'job1'}
jt = JTemplate("{{name2}} is {{age2}} years old and works as a {{job2}}.")
result1 = jt.render(data)
print(result1) #first print statement
st = STemplate(result1)
result2 = st.substitute(data)
print(result2) #second print statement
```
If the above Python code runs on the terminal, which of the following statements is/are correct?
The first print statement will output: "name1 is age1 years old and works as a job1."

The second print statement will output: "Alice is 25 years old and works as a Engineer."

Jinja2 templates use double curly braces {{}} for variable substitution
String templates use dollar signs $ for variable substitution in the substitute() method

The code will raise a KeyError exception during execution

Which of the following Flask view functions will NOT throw any error for the URL: `http://127.0.0.1:5000/user?username=mad1&role=admin?`

```python
@app.route('/user')
def profile():
creds = request.args
info = {'username': creds["username"], 'role': creds["role"]}
return info
```
```python
@app.route('/user/<username>/<role>')
def profile(username, role):
info = {'username': username, 'role': role}
return info
```
```python
@app.route('/user')
def profile():
return {'message': 'data retrieved successfully'}
```
All of these

Consider the following HTML and CSS code:
```html
<html>
<head>
<style>
div {
width: 0px;
margin: 0px;
}
.container {
width: 200px;
padding: 15px;
border: 5px solid black;
}
#box {
margin: 10px;
}
</style>
</head>
<body>
<div class="container" id="box">Hello World</div>
</body>
</html>
```
What is the **total width (approximately)** of the `div` with `class="container"` and `id="box"`, including **content, padding, and border** but excluding margin?
Consider the following code:
```python
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
name = request.form['name']
template = "Hello, {{ name }}!"
return render_template_string(template, name=name)
return '''
<form method="POST">
Enter Your Name: <input type="text" name="name">
<button>Submit</button>
</form>
'''
if __name__ == '__main__':
app.run(debug=True)
```
You are building a Flask web application that takes user input from an HTML form and displays it using Jinja2 templates. Suppose the user runs this app locally and submits the name **Alice** in the form.
Which of the following represents the correct sequence of concepts that occur when the user submits the form with the name **Alice** ?
HTML Form Rendering → HTTP 404 Not Found Error → User Submits Form → Flask Routing → Template Rendering

User Submits Form (HTTP POST) → Check URL Structure → Network Transfer (Bandwidth & Latency) → Flask Routing

User Accesses URL (Form at "/") → User Submits Form (HTTP POST) → Flask Request Handling (request.form) → Jinja2 Template Rendering

Flask Request Handling → Network Round Trip (RTT) → HTML Table Rendering → Jinja2 Template Rendering

Consider the web URL. http://localhost:5000/ Which of the following is/are **True**?

http is the protocol.

5000 is the port number.

The trailing / represents the base URL.

5000 is the status code.

Consider the following HTML snippet: ```html <img src="logo.png" alt="Company Logo" /> ``` Which of the following is true?

If logo.png fails to load, the text "Company Logo" will be shown.

If the image file is missing, browsers display it as a broken image.

The alt attribute is mandatory in HTML5.

Logo.png fails to load because the `<img>` tag only allows "jpeg/jpg" files.


If the given Flask app is run using the command ``` python server.py GET PUT POST ``` in one terminal, what will be the output on another terminal for the command ``` curl -X POST http://127.0.0.1:5000/api/data? ```

```html <h1>Data added successfully</h1> ```

```html <h1>Unsupported operation</h1> ```

```html <h1>Method not Allowed</h1> ```

```html <h1>404 Not Found</h1> ```

If the given Flask app is run using the command ``` python server.py GET PUT POST ``` in one terminal, what will be the output on another terminal for the command ``` curl -X DELETE http://127.0.0.1:5000/api/data? ```

```html <h1>Data deleted successfully</h1> ```

```html <h1>Unsupported operation</h1> ```

```html <h1>Method not Allowed</h1> ```

```html <h1>404 Not Found</h1> ```


method="GET" is not correct, it should be methods=["GET"]

```python def login(id) ``` can throw error because no id is passed in, /login url

name will throw error because no name will be written in the starting of app

There is no error, Flask application will run correctly.

Assume the **terminal error** (so the Flask server starts) has already been **fixed**. Now, if you hit the `/login` URL in the browser, which of the following is the correct option in this case?

method="GET" is not correct, it should be methods=["GET"]

```python def login(id) can throw error because no id is passed in /login url ```

name will throw error because no name will be written in the starting of app

There is no error, Flask application will run correctly.
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 (where applicable) for the Diploma Level: Modern Application Development I (Computer-Based Exam). This exam focuses on Flask, Jinja2, HTML/CSS, HTTP, and Python templating.
Routing:
@app.route('/path').@app.route('/profile/<username>').request.args.get('param').@app.route('/', methods=['GET', 'POST']).Example:
@app.route('/user')
def user():
username = request.args.get('username') # Query param
return f"Hello, {username}"Request Handling:
request.method: Check if GET, POST, etc.request.form: Access form data (for POST requests).request.args: Access query parameters (for GET requests).Running the Server:
app.run(port=5000, debug=True).5000; customizable (e.g., 5008).http://localhost:port or http://127.0.0.1:port.Common Errors:
404 Not Found: No matching route.405 Method Not Allowed: HTTP method not supported for the route.KeyError: Missing query/form parameter.Key Equations/Logic:
protocol://host:port/path?query_params Example: http://localhost:5000/user?username=alice/profile/<username>/active/<year> matches /profile/alice/active/2024.Syntax:
{{ variable }}.{{ list | length }} or {{ list | len }} (note: length is correct in Jinja2; len is a Python function).Control structures:
{% if condition %} ... {% endif %}
{% for item in list %} ... {% endfor %}Template Rendering:
render_template('file.html', var=value).render_template_string("Hello, {{ name }}", name="Alice").Inheritance:
{% extends 'base.html' %} and {% block content %}...{% endblock %}.string.Template | |------------------|---------------------------------|---------------------------------| | Syntax | {{ var }} | ${var} or $var | | Filters | {{ list | length }} | No built-in filters | | Logic | {% if %}, {% for %} | No logic; substitution only |<div>, <p> | <span>, <strong> | | Start on new line | Flow inline | | Full width | Width as per content |Box Model:
Total Width Calculation: width + padding-left + padding-right + border-left + border-right + margin-left + margin-right Example:
.container {
width: 200px;
padding: 15px; /* 15px left + 15px right = 30px */
border: 5px solid; /* 5px left + 5px right = 10px */
margin: 10px; /* Excluded from total width */
}
Total width = 200 + 30 + 10 = 240px (excluding margin).
Image Tag:
<img src="path" alt="text">.alt text is shown if the image fails to load.URL Structure: http://localhost:5000/path?query=value
http: Protocol.localhost: Host.5000: Port./path: Route.?query=value: Query parameters.HTTP Methods:
GET: Retrieve data (query params).POST: Submit data (form body).PUT: Update data.DELETE: Remove data.Status Codes:
200 OK: Success.404 Not Found: Route doesn’t exist.405 Method Not Allowed: HTTP method not supported.Jinja2 vs. string.Template:
string.Template: Simpler, uses $var or ${var}.Example:
from jinja2 import Template as JTemplate
from string import Template as STemplate
jt = JTemplate("{{ name }}") # Jinja2
st = STemplate("$name") # string.TemplateRendering Workflow:
POST request).request.form).sys.argv:
sys.argv[0]: Script name.sys.argv[1:]: Command-line arguments.Example:
# python script.py arg1 arg2
print(sys.argv[0]) # script.py
print(sys.argv[1]) # arg1Common Issues:
Route Mismatch:
@app.route('/login', method='GET') → Should be methods=['GET'].Missing Parameters:
def login(id): but no id in the URL.Incorrect HTTP Methods:
curl -X POST to a route that only allows GET.Debugging:
debug=True for detailed errors.request.method and route definitions. total_width = width + padding_left + padding_right + border_left + border_right ` Example: ` width = 200px, padding = 15px, border = 5px total_width = 200 + 15 + 15 + 5 + 5 = 240px `` http://host:port/path?key1=value1&key2=value2 ` Access in Flask: `python value1 = request.args.get('key1') ``