Use When You Want A Full - Edged Data Model Class With Associated Methods
Use When You Want A Full - Edged Data Model Class With Associated Methods
Table :
Use db.Model when you want a full-fledged data model class with associated
methods.
Use db.Table when you just need a table structure without the additional features of a
model class.
—>
1. Client-Server Architecture:
- Definition: Client-server architecture divides a networked application into clients (requesters)
and servers (providers). Clients request services, and servers fulfill those requests,
communicating over a network using protocols like HTTP.
- Roles:
- Client:Initiates requests.
-Server: Listens for requests, processes them, and responds.
-Communication:Clients and servers communicate over a network.
2. Distributed Architecture:
- Definition: Distributed architecture involves multiple interconnected computers working
together. It decentralizes processing tasks, enhances scalability, and incorporates fault
tolerance mechanisms.
- Characteristics:
- Decentralization: Processing and data spread across machines.
- Scalability: Can handle increased load by adding more machines.
- Fault Tolerance: Incorporates redundancy and fault tolerance.
- Types:
- Client-Server Model:Clients and servers collaborate.
- Peer-to-Peer Model: All nodes act as clients and servers, sharing resources directly.(Torrent
Sites)
These architectures improve performance, scalability, and fault tolerance by distributing tasks
across a network.
CRUD Functionality:
- Definition: CRUD stands for Create, Read, Update, Delete — the fundamental operations for
managing data.
- Explanation:
- Create (C):Add new data.
- Read (R): Retrieve existing data.
- Update (U):Modify data.
- Delete (D): Remove data.
- Application:
- Create: Add a new user.
- Read: Retrieve user information.
- Update: Modify user details.
- Delete: Remove a user account.
- Implementation:
- Database: Uses SQL queries.
- Web Development:Implemented through forms and APIs.
- Importance:
- Fundamental for data management.
- Basis for database interactions in software systems.
-Model:
- Manages data and business logic.
- Receives requests from the controller.
- Performs necessary operations on data.
- Updates data state.
- Notifies the controller of changes.
- View:
- Displays data to the user.
- Receives user input.
- Sends user input to the controller.
- Updates based on changes in the model.
- Controller:
- Receives user input from the view.
- Processes input and makes decisions.
- Interacts with the model to update data.
- Updates the view based on changes in the model.
- Facilitates communication between model and view.
Flow:
1. User Interaction:
- User interacts with the view (e.g., clicks a button).
- View sends user input to the controller.
2. Controller Processing:
- Controller receives user input.
- Decides on actions based on input.
- Interacts with the model to update data.
3. Model Update:
- Model performs required operations.
- Updates data state.
- Notifies the controller of changes.
4.View Update:
- Controller updates the view.
- View displays the updated data to the user.
Key Points:
- Separation of Concerns:
- Model handles data and logic.
- View handles user interface and presentation.
- Controller manages user input and coordinates the flow.
-Flexibility:
- Changes in one component do not necessarily affect the others.
- Supports code reusability and modularity.
- Communication:
- Components communicate through well-defined interfaces.
- Enables a clear structure and organization in application development.
Understanding this flow is essential for maintaining a structured and organized application
using the MVC pattern.
Relationships In Databases :
-Relationships in Databases:
- Definition:
- Relationships define how data in different tables of a database are related to each other.
- They establish connections between tables to represent real-world associations.
- Types of Relationships:
1. One-to-One (1:1):
- Example: A person has one passport, and a passport is issued to one person.
- Represented by linking primary keys in both tables.
2. One-to-Many (1:N):
- Example: A department has many employees, but an employee belongs to only one
department.
- Represented by having the primary key in the "one" table as a foreign key in the "many" table.
3. Many-to-Many (M:M):
- Example: Students can enroll in multiple courses, and a course can have multiple
students.
- Represented by introducing a junction table with foreign keys from both related
tables.
- Foreign Keys: - A foreign key is a field in a table that refers to the primary key in
another table.
- It establishes the link between related tables.
- Key Concepts:
- Referential Integrity:
- Ensures that relationships between tables remain consistent.
- Foreign key values must match primary key values.
- Cascade Operations:
- Define what happens when a record in the referenced table is updated or deleted.
- Options include cascading updates or deletions to maintain integrity.
- Benefits:
- Data Integrity:
- Ensures accuracy and consistency of data across related tables.
- Query Efficiency:
- Simplifies querying by allowing retrieval of related data through JOIN operations.
- Definition:
- RESTful API stands for Representational State Transfer Application Programming Interface.
- It is an architectural style for designing networked applications.
- Key Principles:
1. Statelessness:
- Each request from a client to a server contains all the information needed to understand and
fulfill the request.
- No session state is stored on the server between requests.
2. Resource-Based:
- Resources (data or services) are identified by URIs (Uniform Resource Identifiers).
- Operations (GET, POST, PUT, DELETE) are performed on these resources.
3. Uniform Interface:
- A consistent and uniform approach to interacting with resources.
- Includes standard conventions like HTTP methods for operations.
4. Representation:
- Resources may have multiple representations (e.g., JSON, XML).
- Clients interact with these representations.
- HTTP Methods:
- GET:Retrieve a resource.
- POST: Create a new resource.
- PUT: Update an existing resource.
- DELETE: Remove a resource.
- Example:
- Endpoint:`/users`
- GET:Retrieve a list of users.
- POST: Create a new user.
- PUT: Update user information.
- DELETE: Delete a user.
-Benefits:
-Scalability: Stateless nature allows for easy scalability.
-Flexibility: Supports various data formats.
-Simplicity: Uses standard HTTP methods and status codes.
- Use Cases :
- Web Services: Providing data and services over the web.
- Mobile App Backends: Serving data to mobile applications.
- Challenges:
- Complex Operations: Some operations may not fit well into RESTful paradigms.
- Security:Requires proper authentication and authorization mechanisms.
Understanding RESTful API principles is crucial for designing scalable, interoperable, and
maintainable web services. It promotes simplicity, which is key for effective communication
between clients and servers.
Normalization →
- Definition:
- Normalization is the process of organizing data in a database to reduce redundancy and
dependency.
- Goal:
- Minimize data duplication.
- Avoid data anomalies.
- Levels:
- First Normal Form (1NF): Eliminate duplicate columns.
- Second Normal Form (2NF): Eliminate partial dependencies.
- Third Normal Form (3NF): Eliminate transitive dependencies.
- Benefits:
- Reduces storage space.
- Improves data integrity.
- Eases data maintenance.
- Use Case:
- Designing efficient and maintainable databases.
Normalization ensures databases are structured to minimize redundancy and enhance data
consistency.
Mostly 3nf is used cause it balances the database by reducing redundancy and maintaining
simplicity.
ACID VS BASE →
ACID:
- Atomicity:Treats transactions as a single unit. If any part fails, the whole transaction is rolled
back.
- Consistency: Ensures the database moves from one valid state to another after a transaction.
- Isolation: Transactions run independently without affecting each other.
- Durability: Committed transactions persist, even after system failures.
Example:
- If you transfer money between accounts, either the entire transaction succeeds (atomic) or
fails, maintaining consistency.
BASE:
- Basically Available: The system remains operational, providing basic functionality even during
failures.
- Soft state: The system's state may change over time without inputs.
- Eventually consistent: The system will become consistent over time, given no new updates.
Example:
- In a distributed system like cloud storage, updates may take time to propagate, leading to
eventual consistency.
Trade-offs:
- ACID: Emphasizes strong consistency, used in banking systems.
- BASE: Emphasizes availability, used in social media platforms.
Understanding ACID for critical data and BASE for scalable, distributed systems helps in
choosing the right approach for different applications.
1. Primary Key:
- Definition: A primary key is a column or set of columns in a database table that uniquely
identifies each record in the table.
- Uniqueness: Must be unique for each record in the table.
- Null Values: Typically, a primary key column cannot have NULL values.
- Number per Table:Each table can have only one primary key.
- Purpose: Used to uniquely identify records and establish relationships between tables.
2. Unique Key:
- Definition:A unique key is a constraint that ensures that all values in a column or a set of
columns are distinct from one another.
- Uniqueness:Requires values to be unique, but unlike a primary key, it allows for one NULL
value.
- Null Values:Allows for one NULL value per unique key column.
- Number per Table: A table can have multiple unique keys.
- Purpose:Used to enforce the uniqueness of values but not necessarily for record
identification.
In summary, both primary keys and unique keys enforce uniqueness, but a primary key is the
main identifier for a record and cannot contain NULL values, while a unique key allows for one
NULL value and is used to ensure distinct values without necessarily serving as the main
identifier.
- Definition:
- An exception is an abnormal event or error condition that occurs during the execution of a
program and disrupts its normal flow.
- Purpose:
- Handle unexpected situations gracefully.
- Improve program robustness.
- Example
try:
# Code that may raise an exception
x = 10 / 0
except ZeroDivisionError as e:
# Handling the specific exception
IN JAVA THEY USE CATCH
print(f"Error: {e}")
except Exception as e:
# Handling other exceptions
print(f"Unexpected Error: {e}")
finally:
#Code that will be executed regardless of whether an exception occurred
print("Finally block")
```
- Key Components:
- Try: Contains the code where an exception may occur.
- Except: Catches and handles specific exceptions.
- Finally: Contains code that will be executed whether an exception occurred or not.
- Benefits:
- Prevents program crashes.
- Facilitates controlled handling of errors.
Understanding exceptions and how to handle them is crucial for writing robust and error-tolerant
code.
Errorhandler :
Error handler is user to handle the errors which may occur while running a web app all the errors
are
In a web application, HTTP status codes are used to indicate the outcome of a request. They are
three-digit numbers that provide information about the status of the request-response cycle.
Here's a list of common HTTP status codes, including those associated with errors:
1xx (Informational):
- 100 Continue: The server has received the request headers and the client should proceed to
send the request body.
2xx (Successful):
- 200 OK: The request was successful.
- 201 Created:The request was successful, and a resource was created.
- 204 No Content: The request was successful, but there is no new information to send back.
3xx (Redirection):
- 301 Moved Permanently:The requested resource has been permanently moved to a new
location.
- 304 Not Modified: The client's cached copy is up-to-date; the requested resource has not been
modified since.
CLUSTER →
In the context of databases, a "cluster" typically refers to a method of organizing or storing data
in a way that improves performance. There are two main types of clusters: index clusters and
table clusters.
Clusters are database-specific features, and their availability and implementation details depend
on the database management system (DBMS) being used. They are often used to optimize
query performance by organizing data in a way that aligns with common access patterns. It's
important to note that the use of clusters should be carefully considered based on the specific
requirements and workload characteristics of the application.
1. Index Cluster:
- Analogy:Imagine a library where books are organized on shelves based on the first letter of
the author's last name.
- Purpose: This is similar to an index cluster. By grouping books with the same initial letter on
the same shelf, it's quicker to find a book when you know the author's last name.
2. Table Cluster:
- Analogy:Now, consider a library where, instead of each book having its own shelf, books
related to a specific topic or genre are placed together on a shared shelf.
- Purpose: This is akin to a table cluster. If you often look for books on a particular topic,
having them physically close on the shelf makes it more efficient to find related books.
In Database Terms:
- Index Cluster: Physically grouping rows in a table based on indexed columns (e.g., grouping
customer data by region for faster retrieval).
- Table Cluster: Physically storing related rows from multiple tables together (e.g., storing order
and customer data in close proximity for efficient joins).
In both cases, the goal is to optimize the physical storage of data to improve retrieval times
based on common access patterns, just like organizing books in a library to make it easier for
people to find what they're looking for.
Authentication vs Authorization
1. Authentication:
2. Authorization:
- Definition: Authorization is the process of granting or denying access rights and permissions
to a user, system, or application.
- Objective: It determines what actions or resources an authenticated entity is allowed to
access.
- Methods: Authorization is often implemented through roles, permissions, and access control
lists.
- Example: After logging into an email account, authorization determines whether the user can
read, compose, or delete emails.
Key Differences:
- Authentication:
- Focuses on verifying identity.
- Answers the question, "Who are you?"
- Occurs at the beginning of a session.
- Authorization:
- Focuses on granting access rights.
- Answers the question, "What are you allowed to do or access?"
- Occurs after successful authentication.
Analogy
:
-Authentication: Checking your ID at the entrance of a secure building to ensure you are who you
claim to be.
-Authorization: Receiving a specific access card after authentication, which determines which
rooms you are allowed to enter within the building.
In a table:
https://www.w3schools.com/html/html_table_padding_spacing.asp
ALL ENDPOINTS →
1. GET:
- Purpose: Fetch information.
- Example: Browsing a library to get a book's details.
2. POST:
- Purpose: Submit new information.
- Example: Submitting a form to create a new social media post.
3. PUT:
- Purpose: Update or create information.
- Example: Editing your profile details or creating a new profile.
4. DELETE:
- Purpose: Remove information.
- Example: Deleting an email or removing a contact.
5. PATCH:
- Purpose: Make a small update.
- Example: Changing your password without updating the entire profile.
6. HEAD:
- Purpose: Get only headers, no details.
- Example: Checking if a store is open without getting the full store info.
7. OPTIONS:
- Purpose: Check available actions.
- Example: Seeing options for interacting with an ATM.
8. TRACE:
- Purpose: Diagnose, echo back.
- Example: Checking if a message sent is received as intended.
Key Takeaway:
- GET: Fetch data.
- POST: Add new data.
- PUT: Update or create data.
- DELETE: Remove data.
- PATCH: Make a small update.
- HEAD: Get only headers.
- OPTIONS: Check available actions.
- TRACE: Diagnose, echo back.
Understanding these methods is like knowing different actions you can perform when
interacting with various services or systems, much like actions you take in everyday situations.
CSS styles can be applied to HTML documents in three main ways: inline, internal (or
embedded), and external. The hierarchy determines which styles take precedence when
conflicts arise.
1. Inline Styles:
- Definition: Styles applied directly to individual HTML elements using the `style` attribute.
- Hierarchy Note: Inline styles have the highest specificity and override other styles.
3. External Styles:
- Definition: Styles stored in a separate CSS file and linked to the HTML document using the
`<link>` tag.
- Example: <link rel="stylesheet" type="text/css" href="styles.css">
- Hierarchy Note: External styles have the lowest specificity and are overridden by both inline
and internal styles.
Inline styles have the highest specificity and override both internal and external styles. Internal
styles take precedence over external styles but are overridden by inline styles. External styles
have the lowest specificity and are applied globally but can be overridden by both inline and
internal styles when conflicts arise.
The CSS hierarchy for HTML tags is determined by specificity and the order in which styles are
applied. Specificity is a measure of how specific a selector is, and it plays a crucial role in
determining which styles take precedence. Here's a general hierarchy:
1. Inline Styles:
- Specificity: Highest specificity.
- Example:
html
<p style="color: red; font-size: 16px;">This is a paragraph with inline styles.</p>
- Hierarchy Note: Inline styles applied directly to an element override all other styles.
2. ID Selectors:
- Specificity: Higher specificity.
- Example:
css
#myElement {
color: blue;
font-size: 18px;
}
- Hierarchy Note: ID selectors are more specific than type or class selectors.
3. Class Selectors:
- Specificity: Moderate specificity.
- Example:
css
.myClass {
color: green;
font-size: 20px;
}
- Hierarchy Note: Class selectors are less specific than ID selectors but more specific than
type selectors.
- Hierarchy Note: The universal selector targets all elements and has the lowest specificity.
Hierarchy Summary:
- Inline styles have the highest specificity and override all other styles.
- ID selectors have higher specificity than class and type selectors.
- Class selectors have higher specificity than type selectors.
- Type selectors have lower specificity compared to ID and class selectors.
- The universal selector has the lowest specificity.
1. GET:
2. POST:
3. PUT:
4. PATCH:
5. DELETE:
These methods are often referred to as CRUD (Create, Read, Update, Delete) operations, as they
represent the basic operations that can be performed on resources. When working with RESTful
APIs, each resource is identified by a unique URI (Uniform Resource Identifier), and these HTTP
methods are applied to these URIs.
Additionally, there are other HTTP methods like OPTIONS, HEAD, and others, but the five
mentioned above are the primary ones used in most RESTful APIs. It's important to understand
the use case for each method and when to appropriately apply them based on the operations
you want to perform on the server's resources.
SQLAlchemy is a Python library that simplifies working with databases in your Python
applications. It provides tools for interacting with databases using Python code, making
database operations more natural and aligned with Python's syntax. SQLAlchemy also includes
an Object-Relational Mapping (ORM) system, allowing you to work with databases using Python
classes and objects, which makes database interactions more intuitive and expressive. Overall,
it helps manage database-related tasks in a Pythonic way.
python
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
2. Object-Relational Mapping (ORM): - You can use Python objects to perform database
operations. For instance, adding a new user to the database:
python
new_user = User(username='john_doe', email='[email protected]')
db.session.add(new_user)
db.session.commit()
python
all_users = User.query.all()
4. Database Agnostic:
- You can switch between different database backends without major code changes. If you
decide to use PostgreSQL instead of SQLite, the code remains largely the same.
python
app.config['SQLALCHEMY_DATABASE_URI'] =
'postgresql://username:password@localhost/dbname'
python
result = db.session.execute('SELECT * FROM users WHERE username=:username',
{'username': 'john_doe'})
These examples showcase how SQLAlchemy simplifies database interactions in Python by
providing a Pythonic, object-oriented approach, abstracting SQL complexities, supporting
different databases, and offering flexibility for more advanced scenarios.
Python
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return f'<User {self.username}>
In this example:
The `User` class inherits from `db.Model`, making it a database model. The class attributes
(`id`, `username`, `email`) represent columns in the database table. The `__repr__` method is a
string representation used for debugging purposes.
Here's a breakdown:
- `User` inherits from `db.Model`, inheriting all properties and methods from the SQLAlchemy
`Model` class.
- `db.Column` is used to define the columns of the database table. It specifies the data type
(`db.String`, `db.Integer`, etc.) and optional constraints (e.g., `primary_key`, `unique`, `nullable`).
This setup allows you to interact with the database using object-oriented syntax. For instance,
you can create a new user and add it to the database:
python
new_user = User(username='john_doe', email='[email protected]')
db.session.add(new_user)
db.session.commit()
``
Here, `db.session.add()` adds the user to the session, and `db.session.commit()` persists the
changes to the database. The ORM takes care of translating these operations into SQL queries,
providing a convenient and Pythonic way to work with databases.
ORM
Object-Relational Mapping (ORM) is a programming technique that allows you to interact with a
relational database using objects in your programming language, instead of writing raw SQL
queries.
ORM is used to bridge the gap between the object-oriented model used in programming
languages (like Python, Java, or C#) and the relational model used in databases (like MySQL,
PostgreSQL, or SQLite). It simplifies database interactions by representing database tables as
classes and database rows as instances of those classes.
Certainly! Let's use Python and SQLAlchemy to illustrate a simple example of working with an
ORM.
1. Defining a Model Class (Object):
- Using an ORM like SQLAlchemy, you define a Python class to represent a table in the
database. Each instance of this class corresponds to a row in that table.
python
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(80), unique=True, nullable=False)
email = Column(String(120), unique=True, nullable=False
python
engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(bind=engine)
session = Session(bind=engine)
python
all_users = session.query(User).all()
for user in all_users:
print(user.username, user.email)
In this example:
ORM simplifies the interaction with the database by letting you use objects and classes instead
of raw SQL queries, making it more intuitive and reducing the need for low-level database
operations.
In the context of a web application, particularly one following the MVC (Model-View-Controller)
architecture, the controller (`main.py` in this case) is responsible for handling incoming HTTP
requests, processing them, and sending an appropriate response. When dealing with APIs
(Application Programming Interfaces), this often involves sending and receiving data in a
structured format, commonly in JSON.
```python
# Example using Flask for handling incoming HTTP requests
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/example', methods=['GET'])
def get_example_data():
# Logic to handle GET request and retrieve data
data = {"message": "This is an example API response."}
return jsonify(data)
```
```python
import requests
```python
# Example processing a POST request and saving data to a database
@app.route('/api/example', methods=['POST'])
def create_example_data():
# Extract data from the incoming request
data = request.json
```python
# Example sending a JSON response
@app.route('/api/example', methods=['GET'])
def get_example_data():
# Logic to handle GET request and retrieve data
data = {"message": "This is an example API response."}
return jsonify(data)
```
In summary, the controller file (`main.py`) handles incoming API requests, processes them
(which may involve sending requests to other APIs or interacting with databases), and sends
back appropriate API responses. It acts as the intermediary between the client (which initiates
the API request) and the rest of the application.
APP.ROUTE()
`@app.route()` is a decorator in Flask, a web framework for Python, used to define routes or
endpoints in a web application. In a viva or interview setting:
1. Definition:
- `@app.route()` is a special syntax in Flask that binds a function to a URL route. It tells Flask
which function to execute when a particular URL is accessed.
2. Purpose:
- It is essential for mapping HTTP requests (like GET or POST) to specific functions in your
code. Without `@app.route()`, Flask wouldn't know which function to execute when a particular
URL is requested.
3. Example:
```python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, this is the home page!'
```
In this example, `@app.route('/')` tells Flask that the `home()` function should be executed
when the root URL (`/`) is accessed.
4. Need:
- The need for `@app.route()` arises because it establishes a connection between URLs and
the functions that handle the corresponding requests. It defines the routing logic in a Flask
application, making it easy to create modular and well-organized web applications.
In summary, `@app.route()` is a decorator in Flask that plays a crucial role in defining routes,
associating URLs with specific functions, and directing the flow of requests in a web
application. It's a fundamental aspect of routing in Flask.
template inheritance
Template inheritance is a feature in web development frameworks that allows you to create a base or
parent template containing the common structure of your web pages and then extend or inherit from this
template in other templates to reuse the common elements. This concept is widely used in frameworks
like Flask, Django, and Jinja2.
1. Definition:
- Template inheritance is a mechanism that enables you to create a master or base template with the
overall structure of your web pages. Other templates can then inherit from this base template, inheriting
its structure and allowing customization of specific content sections.
2. Purpose:
- It promotes code reusability and maintainability by avoiding duplication of HTML structure across
multiple pages. Changes made in the base template automatically reflect in all templates that inherit from
it.
3. Example (Using Jinja2 - Flask's Template Engine):
- Base Template (`base.html`):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<!-- Other common navigation links -->
</ul>
</nav>
<main>
{% block content %}{% endblock %}
</main>
<footer>
<p>© 2023 My Website</p>
</footer>
</body>
</html>
```
```html
{% extends 'base.html' %}
{% block content %}
<h2>Welcome to the Home Page!</h2>
<!-- Content specific to the home page -->
{% endblock %}
```
4. Need:
- Template inheritance is needed to maintain a consistent look and feel across different pages of a
website while allowing customization of specific content sections. It reduces redundancy, makes code
more modular, and simplifies updates to the overall site structure.
In summary, template inheritance is a technique that promotes code reusability and maintainability in web
development by allowing templates to inherit from a common base template and customize specific
sections as needed.
LAZY LOADING
In the context of web development, lazy loading is often associated with images, scripts, or
other assets on a webpage. Here's how lazy loading works:
2. Loading on Demand:
- As the user scrolls down the page, additional images that come into the viewport are loaded
dynamically. This is triggered by JavaScript or, in modern web browsers, by using the
`loading="lazy"` attribute on the `<img>` tag.
```html
<img src="placeholder.jpg" data-src="actual-image.jpg" loading="lazy" alt="Lazy Loaded
Image">
```
In this example, the `data-src` attribute holds the actual image URL, and the `loading="lazy"`
attribute instructs the browser to load the image lazily.
2. Loading on Demand:
- Additional JavaScript code or scripts required for specific interactions or functionalities are
loaded only when those functionalities are triggered. This is often achieved using asynchronous
loading or dynamically injecting script tags into the DOM.
- Improved Initial Page Load Time: By deferring the loading of non-essential resources, the
initial page load is faster, providing a better user experience.
- Bandwidth Efficiency: Users are not required to download resources that they may never see,
saving bandwidth and reducing data usage.
- Better Performance: Reducing the amount of data loaded initially can lead to improved
performance, especially on slower network connections.
It's important to note that while lazy loading can significantly enhance performance, it should be
used judiciously. Critical resources and elements required for the initial user experience should
still be loaded upfront to ensure a smooth and functional interface.
A Single Page Application (SPA) is a type of web application or website that interacts
with the user by dynamically rewriting the current page rather than loading entire new
pages from the server. SPAs use AJAX (Asynchronous JavaScript and XML) and
modern web technologies to achieve a more seamless and responsive user experience.
- In SPAs, the initial HTML, CSS, and JavaScript are loaded with the first request, and
subsequent interactions with the application result in the dynamic loading of content.
This is typically achieved through AJAX requests to the server.
3. Client-Side Routing:
- SPAs often implement client-side routing, where the navigation and URL changes
are handled on the client side without making a request to the server. This is done
through JavaScript frameworks like React, Angular, or Vue.js.
4. Improved User Experience:
- SPAs provide a more responsive and interactive user experience, as users can
navigate between different sections of the application without waiting for full page
reloads. This is especially beneficial for complex web applications.
5. State Management:
6. Asynchronous Loading:
- Resources such as images, scripts, and data are loaded asynchronously as needed,
contributing to faster initial page loads and reducing the need for unnecessary data
transfer.
- SPAs are commonly built using front-end JavaScript frameworks and libraries such
as React, Angular, or Vue.js. These tools provide structured ways to organize code,
handle routing, and manage state.
8. SEO Challenges:
- SPAs initially faced challenges with search engine optimization (SEO) because
search engine crawlers traditionally relied on static HTML content. However, modern
solutions and techniques, such as server-side rendering (SSR) and pre-rendering, have
addressed these challenges.
Popular examples of SPAs include:
- Twitter: Twitter employs SPA techniques to update the timeline and interact with
tweets without requiring a complete page refresh.
The use of SPAs has become prevalent in modern web development due to their ability
to deliver a more responsive and engaging user experience, especially for applications
with complex user interfaces and interactions.
FLASK
Flask:
Flask is a lightweight and flexible web framework for Python. It is designed to be simple
and easy to use, providing the essentials for building web applications without imposing
too many constraints. Flask is known for its simplicity, extensibility, and ease of
integration with other libraries and tools. It follows the WSGI (Web Server Gateway
Interface) standard, making it compatible with various web servers.
Benefits of Flask:
- Flask has a simple and straightforward design that allows developers to quickly get
started with building web applications. It follows the "micro" framework philosophy,
giving developers the flexibility to choose components and libraries based on their
project needs.
2. Flexibility:
- Flask is easily extensible, and developers can add features or functionality using
Flask extensions. These extensions cover a wide range of capabilities, from form
handling to database integration.
- Flask uses the Jinja2 templating engine, which allows for dynamic content rendering
and template inheritance. It provides a clean and concise syntax for creating HTML
templates.
6. Active Community
- Flask has a vibrant and active community of developers. This community contributes
to the framework's documentation, extensions, and third-party resources, making it
easier for developers to find solutions to common issues.
Disadvantages of Flask:
In summary, Flask is a powerful and lightweight web framework that suits projects
where flexibility and minimalism are prioritized. Its benefits include simplicity, flexibility,
and an active community, while potential drawbacks include a learning curve for
beginners and the need to choose and integrate additional components for certain
features. The choice of Flask or another framework depends on the specific
requirements and preferences of the project and development team.
Certainly! The terms "2-tier" and "3-tier" refer to different architectural models used in
software development, particularly in the context of client-server architecture and
Model-View-Controller (MVC) design pattern.
1. 2-Tier Architecture:
- Client-Server Model: In a 2-tier architecture, the application is divided into two main
components: the client and the server.
- Communication: The client, which is usually the user interface, directly
communicates with the server. The server is responsible for processing requests and
managing the database.
- Advantages: It is a simple architecture, easy to design and implement. It is often
used for small-scale applications.
Example:
- In a basic web application, the web browser (client) communicates directly with the
database server to retrieve and update data.
2. 3-Tier Architecture:
- Client-Server Model with an Application (or Business Logic) Layer: In a 3-tier
architecture, an additional layer, known as the application or business logic layer, is
introduced between the client and the server.
- Components:
- Client Tier: User interface or presentation layer.
- Application Tier: Business logic layer, which handles application-specific
functionality and processing.
- Database Tier: Responsible for managing data storage and retrieval.
- Communication: The client communicates with the application layer, which in turn
communicates with the database layer.
- Advantages: Better organization and separation of concerns. Changes in one tier do
not necessarily affect the others. Scalability is improved compared to 2-tier architecture.
Example:
- In a web application, the web browser (client) interacts with a web server (application
layer), which then communicates with a separate database server (database layer).
- The MVC design pattern can be implemented within the application layer of a 3-tier
architecture. The Model corresponds to the application layer, the View corresponds to
the client tier, and the Controller manages the communication and interaction between
the Model and the View.
In summary, while both 2-tier and 3-tier architectures involve client-server models, the
key difference lies in the number of layers and the distribution of responsibilities. 3-tier
architecture introduces an additional layer for business logic, providing improved
scalability and maintainability, and the MVC design pattern can be integrated within a
3-tier architecture to further enhance the organization of code.
● The Database Tier is more about the physical storage of data, handling database
transactions, and ensuring data integrity at the storage level.
● The Model in the MVC pattern is a higher-level abstraction that encompasses not
only the data itself but also the business logic and rules governing the
application's behavior. In many cases, the Model interacts with the Database Tier
to retrieve or persist data, but it also includes the application's core logic.
Static and dynamic pages refer to different approaches in web content delivery, and
they have distinct characteristics. Here's a breakdown of each:
Static Pages:
1. Content:
- Predefined Content: The content of static pages is fixed and does not change unless
manually modified by a developer.
- No User-Specific Content: Static pages are the same for all users, and they don't
adapt based on user interactions or preferences.
2. Generation:
- Pre-generated: Content is generated and stored in advance, typically during the
development phase.
- No Server-Side Processing: There is no server-side processing involved when a
user requests a static page. The server simply serves the pre-existing content.
3. Advantages:
- Performance: Static pages can be faster to load because they are already complete
and ready to be sent to the user.
- Simplicity: They are easier to deploy and manage, especially for smaller websites
with limited interactivity requirements.
4. Examples:
- Basic HTML pages without server-side scripting.
- Brochure websites with fixed content.
Dynamic Pages:
1. Content:
- Generated on Demand: Content is generated in real-time based on user requests or
interactions.
- User-Specific Content: Dynamic pages can adapt to user inputs, preferences, and
data from databases.
2. Generation:
- Server-Side Processing: The server processes requests and may execute scripts
(e.g., PHP, Python, Java) to generate content dynamically.
- Database Interaction: Dynamic pages often involve querying databases for
up-to-date information.
3. Advantages
-Interactivity:Well-suited for interactive websites where content changes based on
user actions.
- Personalization:Allows for personalized content based on user profiles and
preferences.
4. Examples:
- Social media platforms with personalized feeds.
- E-commerce websites with shopping carts and user accounts.
Comparison:
- Performance: Static pages generally load faster as they are pre-generated. Dynamic
pages may have a slightly longer load time due to server-side processing.
- Maintenance: Static pages are easier to maintain, while dynamic pages might require
more attention to server-side scripts and database management.
1. Unit Testing:
- Definition: Testing individual units or components of a software independently.
- Real-Time Example: Using JUnit to test a specific function in a Java application. For
instance, testing a function that calculates the total price of items in a shopping cart.
4. Integrated Testing:
In a viva, you can further elaborate on these examples by discussing the objectives of
each type of testing, the methods employed, and the benefits they bring to the software
development process. Additionally, highlighting the importance of these testing types in
ensuring the reliability and quality of software can strengthen your responses.
In Python, lists, tuples, and dictionaries are three different data structures, each with its own
characteristics and use cases. Here's a brief overview of the differences between them:
1. Lists:
- Mutability: Lists are mutable, meaning you can modify their elements (add, remove, or
change) after the list is created.
- Syntax: Defined using square brackets `[]`.
- Use Case: Suitable for sequences of elements where the order and the ability to modify the
elements are important.
my_list = [1, 2, 3, 'hello']
2. Tuples:
- Immutability: Tuples are immutable, meaning once they are created, you cannot modify their
elements.
- Syntax: Defined using parentheses `()`.
- Use Case: Useful for representing fixed collections of items, especially when the order and
structure of the data should remain constant.
my_tuple = (1, 2, 3, 'hello')
3. Dictionaries:
- Key-Value Pairs: Dictionaries are composed of key-value pairs, where each key is
associated with a specific value.
- Syntax: Defined using curly braces `{}` and specifying key-value pairs using colons.
- Use Case: Suitable for representing mappings, associations, or when you need to quickly
look up values based on keys.
my_dict = {'key1': 'value1', 'key2': 42, 'key3': [1, 2, 3]}
Key Differences:
- Mutability:
- Lists are mutable.
- Tuples are immutable.
- Dictionaries are mutable.
- Syntax:
- Lists use square brackets: `[]`.
- Tuples use parentheses: `()`.
- Dictionaries use curly braces: `{}`.
- Use Case:
- Lists are used for ordered sequences of elements that may need to be modified.
- Tuples are used for immutable sequences where the order matters.
- Dictionaries are used for key-value mappings and quick lookups.
- Performance:
- Due to mutability, lists might have slightly more overhead than tuples in terms of memory and
performance.
- Dictionaries are optimized for quick lookups.
1. Uniqueness: Ensures that each record in the table is uniquely identified by the primary key.
No two records can have the same primary key value.
2. Referential Integrity: Enables relationships between tables by providing a way to uniquely link
records in one table to related records in another table.
- Efficient Retrieval: Optimizes data retrieval, as databases can quickly locate and access
specific records using the primary key.
In essence, primary keys are fundamental for maintaining data integrity, supporting relationships
between tables, and facilitating efficient data retrieval in a database.
Why Bootstrap:
- Rapid Development: Bootstrap allows developers to quickly build responsive and visually
appealing websites with less effort, thanks to its pre-styled components.
- Consistency: Ensures a consistent and professional look across different browsers and
devices.
In summary, Bootstrap simplifies and expedites the process of web development by providing a
set of ready-to-use components, ensuring consistency, and supporting a mobile-first approach.
INDEXING
2. Purpose of Indexing:
- Speed up SELECT queries.
- Facilitate efficient data retrieval.
3. Types of Indexes:
- Primary Key Index: Enforces uniqueness and speeds up retrieval using the primary key.
- Unique Index: Ensures the uniqueness of values in a column.
- Clustered Index: Determines the physical order of data rows in a table.
- Non-Clustered Index: Creates a separate structure for indexing without affecting the order of
the data rows.
5. Benefits of Indexing:
- Improved query performance.
- Faster data retrieval.
- Efficient handling of large datasets.
6. Considerations and Best Practices:
- Balance the benefits of indexing with the overhead of maintenance.
- Analyze query patterns to determine the most effective indexes.
- Avoid over-indexing, as it can impact write operations.
Remember, the term "indexing" can have different meanings in various contexts, so it's always
helpful to clarify the specific area of interest. If you have a different context in mind, please
provide more details for a more accurate response.
GIT
1. Definition:
- Git is a distributed version control system used for tracking changes in source code during
software development.
2. Key Concepts:
- Repository (Repo): Storage for project files and version history.
- Commit: Snapshot of changes made to files.
- Branch: Independent line of development.
- Merge: Combining changes from different branches.
3. Basic Commands:
- `git init`: Initialize a new repository.
- `git add`: Stage changes for commit.
- `git commit`: Save changes with a message.
- `git pull`: Fetch and integrate changes from a remote repository.
- `git push`: Update remote repository with local changes.
4. Branching:
- `git branch`: List branches.
- `git checkout`: Switch to a different branch.
- `git merge`: Combine changes from different branches.
5. Remote Repositories:
- `git remote add`: Connect to a remote repository.
- `git clone`: Copy a remote repository to local.
6. Conflict Resolution:
- `git status`: Check the status of changes.
- `git diff`: View differences between versions.
- Resolve conflicts during merges.
7. GitHub:
9. Best Practices:
10. Conclusion:
This provides a brief and structured overview suitable for a viva setting. Adjust as needed based
on the specific expectations of your examination.
Sandboxing
● Should JS be run automatically on every page?
○ Yes: provides significant capabilities
○ No: what if the page tries to load local files and send them out to server?
● Sandbox: secure area that JS engine has access to
● Cannot access files, network resources, local storage
● Similar to a Virtual Machine, but at higher level (JS interpreter)
INITIAL CODE
1. SQLALCHEMY_TRACK_MODIFICATIONS = False:
This configuration is related to SQLAlchemy, which is a popular SQL toolkit and
Object-Relational Mapping (ORM) library for Python. When set to `False`, it disables
Flask-SQLAlchemy's modification tracking feature. Modification tracking can be
resource-intensive, and turning it off when not needed can improve performance. It's typically
recommended to set this to `False` in production to avoid unnecessary overhead.
2. SECRET_KEY = 'QWERTYALPHA':
Flask uses a secret key for cryptographic operations, such as generating secure session
cookies. The `SECRET_KEY` is crucial for security, and it should be kept secret. It's used to
sign cookies and other security-related tokens, preventing attackers from tampering with them.
It's important to choose a strong, random secret key to enhance the security of your application.
3. SECURITY_PASSWORD_HASH = 'bcrypt':
This configuration is related to Flask-Security, an extension for adding security features to Flask
applications. Here, the chosen password hashing algorithm is set to 'bcrypt'. Bcrypt is a secure
and slow hashing algorithm designed for password hashing. It adds a layer of security by
making it computationally expensive for attackers to crack passwords, even if they have the
hashed values.
4. SECURITY_PASSWORD_SALT = 'TOOSALTYPASSWORD':
In the context of Flask-Security, this is the salt value used in conjunction with the chosen
password hashing algorithm (in this case, 'bcrypt'). A salt is a random value unique to each user
that is combined with the password before hashing. This helps prevent attacks like rainbow
table attacks, where precomputed tables of hashed passwords are used. The
'TOOSALTYPASSWORD' is just an example; in practice, a unique and random salt should be
generated for each user.
5. SECURITY_REGISTRABLE = True:
In Flask-Security, this configuration controls whether user registration is allowed. When set to
`True`, it means that users can register for accounts on the application. If set to `False`, user
registration functionality would be disabled. This is useful when you want to control whether new
users can sign up on your platform or if user registration is not a feature your application needs.
plt.switch_backend('agg')
In this case, the 'agg' backend stands for Anti-Grain Geometry, which is a high-quality
rendering engine for C++. When you switch to the 'agg' backend, matplotlib will use
this rendering engine to create and display plots.
After switching to the 'agg' backend, you can create and save plots without the need
for a graphical user interface. This is beneficial in environments where you don't have
access to a display, like when running code on a server.
BY – DARSHAN GANATRA