0% found this document useful (0 votes)
2 views46 pages

Use When You Want A Full - Edged Data Model Class With Associated Methods

The document covers various fundamental concepts in software development and database management, including the differences between db.Model and db.Table, the MVC design pattern, client-server and distributed architectures, CRUD functionalities, and RESTful APIs. It also explains database normalization, the ACID vs BASE principles, primary and unique keys, exception handling, and the importance of error handling in web applications. Additionally, it discusses the concepts of clustering in databases and the distinction between authentication and authorization.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views46 pages

Use When You Want A Full - Edged Data Model Class With Associated Methods

The document covers various fundamental concepts in software development and database management, including the differences between db.Model and db.Table, the MVC design pattern, client-server and distributed architectures, CRUD functionalities, and RESTful APIs. It also explains database normalization, the ACID vs BASE principles, primary and unique keys, exception handling, and the importance of error handling in web applications. Additionally, it discusses the concepts of clustering in databases and the distinction between authentication and authorization.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

db.Model vs db.

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.

How to Shift text in center —>

text align center;


Without css in tag Align=center

What is MVC —> MVC, or Model-View-Controller, is a design pattern in software development


that separates an application into three main components: Model (handles data and logic), View
(displays information to the user), and Controller (manages user input and updates the Model
and View). This separation enhances modularity, reusability, and testability in software
applications.

What is Client-server architecture and distributed architecture :

—>

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.

How does CRUD functionalities work —>

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.

MVC Workflow —>

MVC Logic Flow:

-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.

Understanding relationships is crucial for designing efficient and normalized databases,


ensuring data accuracy, and enabling effective querying.

(See the code of roles and users)

RestFul API —>

RESTful API in a Viva:

- 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.

- Example: - Unnormalized: `CustomerID | CustomerName | OrderDate | ProductName`


- 3NF: `Customer (CustomerID, CustomerName)`, `Order (OrderID, CustomerID, OrderDate)`,
`Product (ProductID, ProductName)`

- 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.

PRIMARY KEY AND UNIQUE KEY →

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.

EXCEPTION AND USE →

- 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.

4xx (Client Errors):


- 400 Bad Request:The request cannot be fulfilled due to bad syntax.
- 401 Unauthorized:Authentication is required and has failed.
- 403 Forbidden:The server understood the request but refuses to authorize it.
- 404 Not Found: The requested resource could not be found on the server.

5xx (Server Errors):


- 500 Internal Server Error:A generic error message indicating a problem on the server.
- 502 Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response
from an inbound server.
- 503 Service Unavailable:The server is not ready to handle the request; it may be temporary,
such as overloading or maintenance.

To handle these errors simple code is there

@app.errorhandler(error status code)


Def func name:
Do whatever you want to do
Render some page or flash or anything

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.

Real-Life Analogy: Library Shelving System

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

Authentication vs. Authorization:

1. Authentication:

- Definition: Authentication is the process of verifying the identity of a user, system, or


application.
- Objective: It ensures that the entity claiming an identity is, indeed, the entity it purports to be.
- Methods: Common authentication methods include passwords, biometrics, two-factor
authentication, and certificates.
- Example: Logging into an email account by entering a username and password.

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 summary, authentication establishes identity, while authorization determines what actions or


resources an authenticated entity is permitted to access. Both are crucial aspects of ensuring
secure and controlled access to systems and resources.

CELL PADDING AND CELL SPACING →

In a table:

Cell Padding == Space between text and cell itself


Cell Spacing == Space between cells

https://www.w3schools.com/html/html_table_padding_spacing.asp

ALL ENDPOINTS →

Certainly! Here's a simplified explanation without bold formatting:

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.

CAN CREATE WITH PUT —> YES

HTML CSS HIERARCHY :

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.

2. Internal Styles (Embedded):


- Definition: Styles defined within the HTML document using the `<style>` tag in the `<head>`
section.
- Hierarchy Note: Internal styles take precedence over external styles but are overridden by
inline 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.

Main Reason for that is while reading the code it overwrites.

HTML TAGS HIERARCHY →

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.

4. Type (Element) Selectors:


- Specificity: Lower specificity.
- Example:
css
p{
color: purple;
font-size: 22px;
}
- Hierarchy Note: Type selectors target all elements of a specific type and are less specific
than ID and class selectors.

5. Universal Selector (*):


- Specificity: Lowest specificity.
- Example:
css
*{
color: gray;
font-size: 14px;
}

- 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.

RESTAPI AND ITS METHODS

REST (Representational State Transfer) is an architectural style for designing networked


applications. RESTful APIs (Application Programming Interfaces) adhere to the principles of
REST and provide a standardized way for software systems to communicate over the web. The
most commonly used HTTP methods in RESTful APIs are:

1. GET:

- Used to retrieve information from the server.


- It should not have any side effects on the server.

2. POST:

- Used to submit data to be processed to a specified resource.


- It can result in the creation of a new resource on the server.

3. PUT:

- Used to update a resource or create a new resource if it does not exist.


- It typically replaces the entire resource.

4. PATCH:

- Similar to PUT, but it is used to partially update a resource.


- It only updates the fields that are provided and leaves others unchanged.

5. DELETE:

- Used to request the removal of a resource on the server.

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.

What is Db.Model And Why its There

`db.Model` is a fundamental component when using an Object-Relational Mapping (ORM)


system, like SQLAlchemy in Python, to connect your application to a database. It acts as a base
class for defining the structure of your database tables in a way that mirrors your application's
data model. By inheriting from `db.Model`, you create classes that represent tables in the
database. Each attribute in these classes corresponds to a column in the table. This approach
simplifies database interactions, allowing you to perform CRUD (Create, Read, Update, Delete)
operations using familiar object-oriented syntax, making it more intuitive and aligned with your
application's code structure.

What is sqlalchemy why it is used

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.

1. Pythonic Database Interaction:


- Instead of writing raw SQL queries, you interact with the database using Python classes and
objects. For example, creating a `User` class to represent a table in the database:

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()

3. Abstraction of SQL Complexity:


- SQLAlchemy abstracts away SQL complexities. To query users from the database, you can
use SQLAlchemy's query API:

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'

5. Flexibility and Control:


- While SQLAlchemy provides high-level abstractions, you can still use raw SQL when needed.
For example, executing a custom SQL query:

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.

From Where DB inherits its properties from

Python

from flask import Flask


from flask_sqlalchemy import SQLAlchemy

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:

1. `app` is a Flask application.


2. `db` is an instance of `SQLAlchemy`, representing the database.

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`).

- The `__repr__` method provides a string representation of a User object.

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

2. Creating and Adding Objects (Instances):


- You can then create instances of this class, which represent rows in the 'users' table, and add
them to the database.

python
engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(bind=engine)

session = Session(bind=engine)

new_user = User(username='john_doe', email='[email protected]')


session.add(new_user)
session.commit()

3. Querying and Retrieving Objects:


- You can query the database to retrieve objects using the ORM, making use of the
object-oriented syntax.

python
all_users = session.query(User).all()
for user in all_users:
print(user.username, user.email)

In this example:

- `User` is a Python class representing the 'users' table in the database.


- Instances of `User` (e.g., `new_user`) are created and added to the database.
- Querying the database returns objects (instances of `User`), allowing you to work with them in
a more natural, object-oriented way.

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.

HOW CONTROLLER SENDS AND RECIEVES API

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.

1. Handling Incoming API Requests:


- The controller receives incoming API requests. These requests are typically HTTP requests
(e.g., GET, POST, PUT, DELETE) sent by clients (e.g., a web browser, a mobile app, or another
server) to interact with the application.

```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)
```

2. Sending API Requests:


- If the controller needs to communicate with external APIs, it can use libraries like `requests`
in Python to send HTTP requests to those APIs. These requests can be GET requests to fetch
data, POST requests to send data, etc.

```python
import requests

# Example sending a GET request to an external API


response = requests.get('https://api.example.com/data')
data_from_api = response.json()
```

3. Processing API Requests:


- The controller processes the incoming API requests, extracting data, performing any
necessary business logic, and preparing a response. This may involve querying a database,
manipulating data, or interacting with other components of the application.

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

# Logic to process and save data to a database


return jsonify({"message": "Data created successfully."})
```

4. Sending API Responses:


- The controller sends API responses back to the client. Responses typically include data in a
structured format, commonly JSON, and appropriate HTTP status codes.

```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.

Here's a simple explanation for a viva or interview:

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>&copy; 2023 My Website</p>
</footer>
</body>
</html>
```

- Inherited Template (`home.html`):

```html
{% extends 'base.html' %}

{% block title %}Home - My Website{% endblock %}

{% 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

Lazy loading is a technique in software development, particularly in web development, where


certain resources or data are loaded only when they are actually needed, rather than loading
everything upfront. This can improve the performance and efficiency of an application by
reducing the initial load time.

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:

Lazy Loading for Images:

1. Initial Page Load:


- When a user opens a webpage, only the images that are initially visible in the viewport (the
part of the webpage currently visible to the user) are loaded. Other images further down the
page are not loaded initially.

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.

Lazy Loading for JavaScript:

1. Initial Page Load:


- Only the essential JavaScript code needed for the initial page load is loaded.

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.

Lazy loading is beneficial for:

- 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.

SINGLE PAGE APPLICATION →

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.

Key characteristics of SPAs include:

1. Dynamic Content Loading:

- 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.

2. No Full Page Reloads:


- Instead of navigating to a new page and triggering a full page reload, SPAs update
the content within the existing page structure. This creates a smoother and more fluid
user experience.

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:

- SPAs often rely on client-side state management libraries or frameworks to maintain


the application's state. This allows for better handling of user interactions, data
persistence, and the ability to maintain state across different views.

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.

7. Frameworks and Libraries:

- 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:

- Gmail: Gmail is an example of a SPA where interactions such as composing emails,


switching folders, and searching are handled dynamically without full page reloads.

- Facebook: Facebook uses SPA principles to provide a seamless experience as users


navigate through their news feed, profiles, and various features.

- 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:

1. Simplicity and Minimalism:

- 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 provides a minimal set of components, allowing developers to choose and


integrate the libraries they need for specific functionalities. This flexibility is beneficial
when working on projects with varying requirements.
3. Extensibility:

- 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.

4. Jinja2 Templating Engine:

- 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.

5. Built-in Development Server:


- Flask comes with a built-in development server, making it convenient for
development and testing. It allows developers to quickly test their applications without
the need for external server configurations.

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.

7. Compatibility with Python Libraries:


- As a Python framework, Flask seamlessly integrates with various Python libraries
and tools. This compatibility simplifies tasks such as database integration,
authentication, and third-party API interactions.

Disadvantages of Flask:

1. Lack of Built-in Features:


- Flask is intentionally lightweight, but this means that certain features found in larger
frameworks (e.g., Django) are not built into Flask. Developers may need to choose and
integrate additional libraries for tasks such as form validation, authentication, and ORM.

2. Learning Curve for Beginners:


- While Flask is designed to be simple, beginners may find it challenging to grasp
certain concepts, especially if they are new to web development. The flexibility of Flask
requires developers to make more decisions on their own.
3. Less Opinionated:
- Flask provides minimal guidance on project structure and organization. While this
flexibility is an advantage for experienced developers, it may be a disadvantage for
those who prefer a more opinionated framework with predefined conventions.

4. Limited Built-in Security Features:


- Flask does not come with built-in security features that some larger frameworks offer.
Developers need to be vigilant about implementing security best practices, such as
input validation, to ensure the security of their applications.

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.

2 Tier 3 Tier Architecture:

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).

3. MVC (Model-View-Controller) Design Pattern:

- Model: Represents the application's data and business logic.


- View: Represents the user interface or presentation layer.
- Controller: Manages user input, updating the model and view accordingly.
- Advantages: Promotes a clear separation of concerns, making the application easier
to maintain and scale. Changes in one component do not necessarily impact the others.

Relation to 3-Tier Architecture:

- 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 VS Dynamic Pages

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.

- Flexibility:Dynamic pages offer more flexibility in terms of interactivity, personalization,


and real-time updates.

- Maintenance: Static pages are easier to maintain, while dynamic pages might require
more attention to server-side scripts and database management.

Types of testing what you have done

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.

2. White Box Testing:


- Definition: Examining the internal logic and structure of a software application.
- Real-Time Example: Reviewing the source code of a banking application to identify
and test individual branches and conditions within a method for correctness.

3. Black Box Testing:


- Definition: Assessing the functionality of a software application without knowledge of
its internal code or logic.
- Real-Time Example: Testing the user interface and functionalities of an e-commerce
website without access to the underlying source code.

4. Integrated Testing:

- Definition: Verifying the interactions between integrated components or systems.


- Real-Time Example:Testing the communication between the front-end and back-end
modules of a healthcare management system to ensure seamless data flow and
processing.

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.

LIST VS TUPLE VS DICTIONARY →

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.

WHAT AND WHY PRIMARY KEYS →


Primary keys are unique identifiers assigned to each record (row) in a database table. The
primary key serves two main purposes:

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.

Why Primary Keys:

- Uniqueness:Ensures data integrity and prevents duplicate entries.

- Efficient Retrieval: Optimizes data retrieval, as databases can quickly locate and access
specific records using the primary key.

- Relationships: Facilitates the establishment of relationships between tables in a relational


database.

In essence, primary keys are fundamental for maintaining data integrity, supporting relationships
between tables, and facilitating efficient data retrieval in a database.

WHAT AND WHY BOOTSTRAP →

Bootstrap is a front-end framework that provides a collection of pre-designed and reusable


components, such as buttons, forms, navigation bars, and more, along with a responsive grid
system. It is widely used in web development for creating visually appealing and mobile-friendly
user interfaces.

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.

- Mobile-First Approach: Bootstrap is designed with a mobile-first approach, making it easy to


create websites that work well on various screen sizes.
- Customization:While offering ready-made components, Bootstrap is also highly customizable,
allowing developers to tailor the design to fit specific project requirements.

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

In the context of a database, "indexing" refers to a database management system (DBMS)


feature that enhances the speed of data retrieval operations on a database table. Indexing
works by creating a data structure (an index) to improve the speed of data retrieval operations
on a database.

1. What is an Index in a Database:


- A data structure that improves the speed of data retrieval operations on a database table.

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.

4. Creating and Managing Indexes:


- Indexes are created using SQL commands like CREATE INDEX.
- Regularly monitor and maintain indexes for optimal performance.
- Be cautious with the number of indexes to avoid overhead.

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:

- Platform for hosting Git repositories.


- Facilitates collaboration and project management.
- Pull Requests for code review and collaboration.

8. Version Control Benefits:

- Collaboration: Multiple contributors work on the same project.


- History: Detailed record of changes over time.
- Rollback: Revert to previous versions if needed.

9. Best Practices:

- Regular commits with meaningful messages.


- Use branches for feature development.
- Pull and push regularly to stay synced.

10. Conclusion:

- Git is a powerful tool for collaborative and version-controlled software development.


- Essential for tracking changes, collaborating with others, and maintaining code integrity.

This provides a brief and structured overview suitable for a viva setting. Adjust as needed based
on the specific expectations of your examination.

Inbuilt HTML5 form controls

● Partial validation added by HTML5 standard


● required: mandatory field
● minlength, maxlength: for text fields
● min, max: for numeric values
● type: for some specific predefined types
● pattern: regular expression pattern
match(https://www.w3schools.com/tags/att_input_pattern.asp)

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

Certainly! Let's break down each configuration point:

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.

These configurations collectively contribute to the security, performance, and functionality


aspects of a Flask application with Flask-SQLAlchemy and Flask-Security extensions.

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.

Here's a brief explanation:

● Matplotlib Backend: Matplotlib has different backends for rendering images.


The backend is responsible for rendering the figure on the screen or saving it to
a file.
● 'agg' Backend: The 'agg' backend is a high-quality rendering engine that can be
useful in situations where other backends might have limitations or
performance issues. It's particularly useful for saving high-quality images.

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

You might also like