WebX.O - Mod5,6
WebX.O - Mod5,6
1) Python Flask
Flask is a lightweight and flexible web framework in Python used to build web applications and APIs.
It is known for its simplicity, modularity, and ease of use.
🔹 Key Features of Flask
1. Lightweight & Minimalistic
o Flask follows a micro-framework philosophy — it comes with the bare essentials,
allowing developers to add components as needed.
2. Built-in Development Server
o Includes a fast debugger and development server for testing applications locally.
3. Routing System
o Uses @app.route() decorators to map URLs to Python functions.
9. Modular Design
o Encourages blueprint-based project structure for scalable applications.
app = Flask(__name__)
@app.route('/setcookie')
def set_cookie():
resp = make_response("Cookie Set")
resp.set_cookie('username', 'JohnDoe') # key, value
return resp
@app.route('/getcookie')
def get_cookie():
username = request.cookies.get('username') # Get cookie value
return f'Hello {username}' if username else 'No cookie found'
3) What are Flask Templates? How do they help in creating dynamic web pages?
Flask templates are HTML files that use the Jinja2 templating engine, integrated with Flask, to create
dynamic content. Templates allow embedding Python-like expressions ({{ }}, {% %}) directly into
HTML.
Purpose and Benefits:
Enable dynamic content rendering (e.g., displaying user data).
Promote separation of concerns: Python code in views, HTML in templates.
Simplify front-end generation based on backend data.
How it works:
render_template('template.html', key=value) passes data to the template.
The template uses {{ key }} to display dynamic data.
You can use control structures like {% if %}, {% for %}.
Example:
app.py=>
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html', name='Alice')
templates/index.html =>
<!DOCTYPE html>
<html>
<body>
<h1>Welcome {{ name }}!</h1>
</body>
</html>
Output: Welcome Alice!
4) What is URL Building in Flask? Explain with an example.
URL building in Flask refers to the process of dynamically generating URLs for functions (routes)
using the url_for() function instead of hardcoding URLs.
Purpose / Benefits:
Avoids hardcoding URLs → more maintainable.
Automatically updates links if route changes.
Supports adding dynamic arguments (query strings, path variables).
How it works: Flask maps URLs to functions. url_for('function_name') returns the URL for that
function.
Example:
app.py =>
from flask import Flask, url_for, redirect
app = Flask(__name__)
@app.route('/profile/<username>')
def profile(username):
return f'Hello {username}'
@app.route('/')
def index():
return redirect(url_for('profile', username='John'))
Explanation:
url_for('profile', username='John') builds /profile/John dynamically.
If route /profile/<username> ever changes, url_for will handle it automatically.
Output:
Redirects to:
/profile/John
Hello John
5) What are the HTTP methods supported by Flask? Explain each with examples.
HTTP methods define the type of action to be performed on a resource. Flask supports several HTTP
methods for handling different types of requests.
Supported HTTP Methods in Flask:
1. GET
o Purpose: Retrieves data from the server (default method).
Example:
@app.route('/get', methods=['GET'])
def get_example():
return 'This is a GET request'
Output: "This is a GET request"
2. POST
o Purpose: Sends data to the server, typically to create or update a resource.
Example:
@app.route('/post', methods=['POST'])
def post_example():
return 'POST request received'
Output: "POST request received"
3. PUT
o Purpose: Updates a resource on the server (replaces current data).
Example:
@app.route('/put', methods=['PUT'])
def put_example():
return 'PUT request received'
Output: "PUT request received"
4. DELETE
o Purpose: Deletes a resource on the server.
Example:
@app.route('/delete', methods=['DELETE'])
def delete_example():
return 'DELETE request received'
Output: "DELETE request received"
5. PATCH
o Purpose: Partially updates a resource.
o Example: Updating just one field of a resource (e.g., updating email in a user
profile).
Example:
@app.route('/patch', methods=['PATCH'])
def patch_example():
return 'PATCH request received'
Output: "PATCH request received"
6. OPTIONS
o Purpose: Returns the allowed HTTP methods for a resource.
o Example: Checking which HTTP methods are supported on an endpoint.
Example:
@app.route('/options', methods=['OPTIONS'])
def options_example():
return 'OPTIONS request received'
Output: "OPTIONS request received"
2) What are the features and working of AJAX? How does it enhance web interactivity?
Features of AJAX:
1. Asynchronous Communication: Data is sent/received in the background without disrupting
user interaction.
2. Partial Page Updates: Only specific page sections are updated, avoiding full page reloads.
3. Supports Multiple Data Formats: Handles XML, JSON, HTML, and text formats.
4. Reduces Server Load: Only necessary data is requested, reducing load and bandwidth.
5. Cross-platform Compatibility: Works across browsers and platforms.
6. Enhanced User Experience: Faster, more responsive applications with reduced waiting times.
Working of AJAX:
1. Client Sends Request: The client sends an asynchronous HTTP request using JavaScript
(XMLHttpRequest/Fetch).
2. Server Processes Request: The server processes and sends the response (usually JSON or
XML).
3. Client Receives Response: The client receives the data without reloading the page.
4. Dynamic Page Update: JavaScript updates the page by manipulating the DOM with the new
data.
How AJAX Enhances Web Interactivity:
1. Faster User Interactions: Instant page updates without reloading, improving response times.
2. Improved User Experience: Smooth interaction by updating only part of the page.
3. Seamless Updates: Continuous interaction with no page interruptions.
4. Real-time Data: Fetches live data, such as updates or notifications, without page refresh.
Summary:
Features: Asynchronous, partial updates, reduced server load, supports multiple formats.
Working: Client → Request → Server → Response → Dynamic update.
Interactivity: Instant updates, improved UX, and real-time data without full reloads.
o status represents the HTTP response code (e.g., 200 for success).
Summary:
XMLHttpRequest sends HTTP requests, allowing asynchronous communication.
The object is used to open, send, and handle responses to dynamically update a web page
without a full reload.
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Register</button>
</form>
Input Validation:
Validation ensures that the data entered is in the correct format before it is processed or submitted.
1. Username Validation:
o Must not be empty and can be checked for a minimum length (e.g., 5 characters).
o Example validation:
o Example validation:
o Example validation:
2. XML:
o Structures and encodes data for easy sharing.
6. Logic:
o Uses formal logic principles for automated reasoning and inference.
7. Proof:
o Provides transparency on how conclusions are derived.
8. Trust:
o Ensures data credibility with mechanisms like digital signatures.
Summary:
The Semantic Web Stack provides a layered architecture for the web, enhancing its ability to process
and understand data intelligently, from basic encoding (Unicode/URI) to reasoning (Logic) and trust
validation (Trust).
Example:
_:john <http://example.org/name> "John" .
2. Human-Readable Text Format
N-Triples uses a simple plain-text format, making it both human-readable and machine-
processable.
Each triple is on a new line and ends with a period.
Example:
<http://example.org/person/john> <http://example.org/age> "25" .
<http://example.org/person/john> <http://example.org/name> "John Doe" .
3. Support for Blank Nodes
N-Triples supports blank nodes (anonymous resources without a URI).
Useful for relationships between resources without needing unique identifiers.
Example:
_ :b1 <http://example.org/hasAge> "30" .
_ :b1 is an anonymous resource.
4. Simple Syntax and Flexibility
The syntax is simple and consistent, with the ability to use URIs, literals, or blank nodes as
objects.
N-Triples can represent diverse data types within RDF format.
Examples of Object Types:
o URI: <http://example.org/person/john>
Conclusion N-Triples is a straightforward, readable, and flexible format for encoding RDF data.
It supports easy data representation, ensuring interoperability within the Semantic Web while
being machine-processable and human-readable.
Time Period 1990s – Early 2000s 2004 – Present Emerging (Current and future)
Security & Low concern Moderate concern High privacy (User ownership
Privacy of data)
Core Focus Information display User engagement and Trust, decentralization, and
sharing ownership
Explanation:
1. Web 1.0 (Static Web):
o The first version of the internet, primarily made up of static, read-only websites.
o Example: Early search engines like Yahoo! and simple informational websites.
2. Web 2.0 (Social Web):
o Introduced dynamic content, social interaction, and user-generated content.
o Users became active participants, contributing content and interacting with websites.
Learning Curve Easy for beginners Slightly harder due to types and syntax
Code Maintainability Harder in large codebases Better suited for large-scale projects
Q2) Difference Between var and let in TypeScript & Function Overloading
1. Difference Between var and let
Redeclaration Allowed in the same scope Not allowed in the same scope
Global Pollution Higher chance of accidental globals Reduces risk of global variable leaks
Example:
function testVarLet() {
if (true) {
var x = 10;
let y = 20;
}
console.log(x); // Output: 10
console.log(y); // Error: y is not defined (block scoped)
}
2. Function Overloading in TypeScript
Function overloading allows a function to have multiple signatures with the same name but different
parameter types or numbers.
How It Works:
Declare multiple function overload signatures.
Provide one implementation that handles all overloads.
Example:
// Overload Signatures
function add(a: number, b: number): number;
function add(a: string, b: string): string;
// Single Implementation
// Base Class
class Animal {
eat() {
console.log("Animal is eating");
}
}
// Derived Class
class Dog extends Animal {
bark() {
console.log("Dog is barking");
}
}
// Arrow function
let add = (a: number, b: number): number => {
return a + b;
};
Q5) Explain how internal and external modules are used in TypeScript with suitable examples.
In TypeScript, modules help organize code into reusable, maintainable, and isolated units. There
are two types of modules:
1. Internal Modules (Namespaces) – used within a single file.
2. External Modules – used across multiple files using import and export.
1) Internal Modules (Namespaces)
An internal module (also called a namespace) groups related classes, interfaces, or functions within
a single file. This helps avoid naming conflicts and improves code organization.
Example:
namespace Animal {
export class Dog {
bark() {
console.log("Woof! Woof!");
}
}
Conclusion: Both internal (namespaces) and external modules serve the purpose of code
organization. However, external modules are now the standard approach in TypeScript for building
scalable, maintainable applications due to ES6 module support and modern tooling.
let i = 0;
while (i < 5) {
console.log(`Iteration ${i}`);
i++;
}
Output: Same as the for loop above
Use Case: When the number of repetitions is known but a for loop is not suitable.
2) Indefinite Loops
An indefinite loop executes an unknown number of times, depending on a condition that changes
during runtime.
Example 1: while Loop with break
let i = 0;
while (i < 5) {
console.log(`Iteration ${i}`);
if (i === 2) {
break; // Exit the loop early
}
i++;
}
Output:
Iteration 0
Iteration 1
Iteration 2
Explanation:
The loop starts with i = 0 and continues while i < 5
When i === 2, the loop breaks manually
Example 2: do-while Loop
let i = 0;
do {
console.log(`Iteration ${i}`);
i++;
} while (i < 5 && i !== 3);
Output:
Iteration 0
Iteration 1
Iteration 2
Explanation:
The do block runs at least once
The loop continues while i < 5 and i !== 3
When i === 3, the loop ends
Key Differences
Examples for, while (with known limit) while, do-while, with break
Conclusion:
Definite loops like for and while are used when the number of iterations is known
beforehand.
Indefinite loops like while and do-while are used when the loop must continue until a
condition is met.
Understanding both types is essential for writing efficient and flexible code in TypeScript.