0% found this document useful (0 votes)
10 views18 pages

Webx 2-1

The document explains URL building in Flask using the url_for() function to dynamically create URLs for specific functions, avoiding hard-coded URLs. It also covers AJAX, describing it as a combination of technologies that enables asynchronous communication between web browsers and servers, enhancing user experience by allowing parts of web pages to update without full page reloads. Additionally, it discusses the characteristics of Rich Internet Applications (RIAs) and the features and architecture of Django for web application development.

Uploaded by

prem.patil22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views18 pages

Webx 2-1

The document explains URL building in Flask using the url_for() function to dynamically create URLs for specific functions, avoiding hard-coded URLs. It also covers AJAX, describing it as a combination of technologies that enables asynchronous communication between web browsers and servers, enhancing user experience by allowing parts of web pages to update without full page reloads. Additionally, it discusses the characteristics of Rich Internet Applications (RIAs) and the features and architecture of Django for web application development.

Uploaded by

prem.patil22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

EXPLAIN URL BUILDINGIN FLASK.

Flask URL Building

The url_for() function is used to build a URL to the specific function dynamically. The first
argument is the name of the specified function, and then we can pass any number of keyword
argument corresponding to the variable part of the URL. This function is useful in the sense
that we can avoid hard-coding the URLs into the templates by dynamically building them
using this function. Consider the following python flask script.

Example

1. from flask import *


2. app = Flask(__name__)
3. @app.route('/admin')
4. def admin():
5. return 'admin'
6. @app.route('/librarion')
7. def librarion():
8. return 'librarion'
9. @app.route('/student')
10. def student():
11. return 'student'
12. @app.route('/user/<name>')
13. def user(name):
14. if name == 'admin':
15. return redirect(url_for('admin'))
16. if name == 'librarion':
17. return redirect(url_for('librarion'))
18. if name == 'student':
19. return redirect(url_for('student'))
20. if __name__ =='__main__':
21. app.run(debug = True)

The above script simulates the library management system which can be used by the three
types of users, i.e., admin, librarion, and student. There is a specific function named user()
which recognizes the user the redirect the user to the exact function which contains the
implementation for this

For example, the URL http://localhost:5000/user/admin is redirected to the URL


http://localhost:5000/admin, the URL localhost:5000/user/librarion, is redirected to the URL
http://localhost:5000/librarion, the URL http://localhost:5000/user/student is redirected to the
URL http://localhost/student.

Benefits of the Dynamic URL Building

1. It avoids hard coding of the URLs.


2. We can change the URLs dynamically instead of remembering the manually changed
hard-coded URLs.
3. URL building handles the escaping of special characters and Unicode data
transparently.
4. The generated paths are always absolute, avoiding unexpected behavior of relative
paths in browsers.
5. If your application is placed outside the URL root, for example, in /myapplication
instead of /, url_for() properly handles that for you.

EXPLAIN AJAX IN DETAIL WITH DIAGRAM AND CREATE A BASIC ALAX


PROGRAM.

AJAX stands for asynchronous Javascript and XML. AJAX is not a programming language
or technology, but it is a combination of multiple web-related technologies like HTML,
XHTML, CSS, JavaScript, DOM, XML, XSLT and XMLHttpRequest object. The AJAX
model allows web developers to create web applications that are able to dynamically interact
with the user. It will also be able to quickly make a background call to web servers to retrieve
the required application data. Then update the small portion of the web page without
refreshing the whole web page.

AJAX applications are much more faster and responsive as compared to traditional web
applications. It creates a great balance between the client and the server by allowing them to
communicate in the background while the user is working in the foreground.

In the AJAX applications, the exchange of data between a web browser and the server is
asynchronous means AJAX applications submit requests to the web server without pausing
the execution of the application and can also process the requested data whenever it is
returned. For example, Facebook uses the AJAX model so whenever we like any post the
count of the like button increase instead of refreshing the whole page.

Working of AJAX

Traditional web applications are created by adding loosely web pages through links in a
predefined order. Where the user can move from one page to another page to interact with the
different portions of the applications. Also, HTTP requests are used to submit the web server
in response to the user action. After receiving the request the web server fulfills the request
by returning a new webpage which, then displays on the web browser. This process includes
lots of pages refreshing and waiting.
AJAX change this whole working model by sharing the minimum amount of data between
the web browser and server asynchronously. It speedup up the working of the web
applications. It provides a desktop-like feel by passing the data on the web pages or by
allowing the data to be displayed inside the existing web application. It will replace loosely
integrated web pages with tightly integrated web pages. AJAX application uses the resources
very well. It creates an additional layer known as AJAX engine in between the web
application and web server due to which we can make background server calls using
JavaScript and retrieve the required data, can update the requested portion of a web page
without casing full reload of the page. It reduces the page refresh timing and provides a fast
and responsive experience to the user. Asynchronous processes reduce the workload of the
web server by dividing the work with the client computer. Due to the reduced workload web
servers become more responsive and fast.

AJAX Technologies

The technologies that are used by AJAX are already implemented in all the Morden
browsers. So the client does not require any extra module to run the AJAX application.The
technologies used by AJAX are −

 Javascript − It is an important part of AJAX. It allows you to create client-side


functionality. Or we can say that it is used to create AJAX applications.
 XML − It is used to exchange data between web server and client.
 The XMLHttpRequest − It is used to perform asynchronous data exchange between
a web browser and a web server.
 HTML and CSS − It is used to provide markup and style to the webpage text.
 DOM − It is used to interact with and alter the webpage layout and content
dynamically.

Advantages of AJAX
The following are the advantages of AJAX −

 It creates responsive and interactive web applications.


 It supports the development of patterns and frameworks that decrease the
development time.
 It makes the best use of existing technology and feature instead of using some new
technology.
 It makes an asynchronous call to the web server which means the client doesn't have
to wait for the data to arrive before starting rendering.

Disadvantages of AJAX

The following are the disadvantages of AJAX −

 AJAX is fully dependent on Javascript. So if anything happens with javascript in the


browser AJAX will not support.
 The debugging of AJAX applications is difficult.
 Bookmarking of AJAX-enabled pages required pre-planning.
 If one request can fail then it can fail the load of the whole webpage.
 If JavaScript is disabled in your web browser then you are not able to run the AJAX
webpage.

Explain the different characteristics of RiA

"Rich Internet Applications" (RIAs) are web applications that have characteristics similar to
traditional desktop applications. They offer a richer user experience by incorporating features
like interactivity, responsiveness, and multimedia content. Here are some of the key
characteristics of RIAs:

1. Interactivity: RIAs enable users to interact with content dynamically without requiring
page reloads. They often use technologies like AJAX (Asynchronous JavaScript and XML)
to update content in real-time based on user actions, enhancing the user experience.

2. Responsiveness: RIAs are highly responsive, providing users with quick feedback to their
actions. This responsiveness is achieved through asynchronous communication with the
server, allowing parts of the application to update independently of the rest.

3. Rich User Interface (UI): RIAs typically feature a visually appealing and intuitive user
interface. They leverage technologies such as Flash, Silverlight, or HTML5 to create
interactive elements like drag-and-drop, animations, and multimedia content, enhancing user
engagement.

4. Offline Capability: Some RIAs are designed to function even when the user is offline or
has a slow internet connection. They can cache data locally and synchronize with the server
when the connection is restored, ensuring uninterrupted user experience.

5. Cross-Platform Compatibility: RIAs are often designed to run across multiple platforms
and devices, including desktops, laptops, tablets, and smartphones. This is achieved through
responsive design techniques or by developing separate versions of the application for
different platforms.

6. Enhanced Functionality: RIAs can incorporate advanced functionality that is not feasible in
traditional web applications. This may include features like drag-and-drop, advanced data
visualization, complex user interactions, and integration with hardware devices (e.g.,
cameras, GPS).

7. Integration with Web Services: RIAs can leverage web services and APIs to access
external data and functionality, enabling seamless integration with other web-based services
and systems.

8. Improved Performance: By minimizing server round-trips and leveraging client-side


processing, RIAs often offer improved performance compared to traditional web applications.
This results in faster load times and smoother user interactions.

List features and architecture of DJANGO requried to develop web application.

Django is most often used for web development, but it can be used for many other purposes
as well. It is a highly-regarded piece of software and is highly recommended for anyone who
is serious about their web development. It can be used to build large e-commerce websites,
blogging sites, or anything else that requires a scalable, high-performing website. In this
article, we are going to cover all the basics you need to know to get started with Django. We
will cover topics such as setting up your development environment and installing and using
Django. We will also cover how to choose the right Django installation for your needs and
how to get the most out of the framework by using best practices. By the end of the article,
you will be confident in using Django to build your websites. You will also have a good
understanding of how Django benefits your team’s performance and how it can be used for
other purposes.

Features of Django Some features that make Django an ideal framework for web application
development are as follows:

1. Super fast: Django development is extremely fast. Our ideas can take the shape of a
product very quickly.
2. Fully loaded: Django has dozens of projects that can be integrated to carry out
common tasks such as user authentication, authorization, and content administration.
3. Versatile: Django can be used for almost any kind of project, from CMSs to e-
commerce apps to on-demand delivery platforms.
4. Secure: Django also has support to prevent common security issues, including cross-
site request forgery, cross-site scripting, SQL injection, and clickjacking.
5. Scalable: Django websites can scale fast to meet high traffic demands.
DJANGO ARCHITECTURE : Every website has three main code sections: input logic,
business logic, and user interface logic. The code has certain functions to perform, the input
data is the dataset and how it is stored in the database. It is just a matter of delivering the
input to the database in the desired format. The Business Logic is what controls the output of
the server in HTML or another format. The HTML and CSS are the pages that it is written
for. These days, the approach taken is different. The content is gathered from multiple
sources and stored in separate files. This is known as page streaming, and it is a widely used
approach for website content. The code for the webpage is stored in one file and the HTML,
CSS and JS are stored in separate files. The content is streamed from the server and rendered
in the browser. These days, the vast majority of software development is done using web
technologies such as JavaScript, HTML, CSS and JAVA, which are familiar to developers. It
may come as a surprise that most of the software development is done using these
technologies. MVC has a model, view, and controller. The Model is the information that your
website/ application will be working with. The View is the presentation of the Model on your
website/application. Finally, the Controller is the code that connects the View and Model
together. In most cases, the Controller is the place where you will be writing your code. Let’s
look at each of these components in detail to understand how they work together to form the
Django MVC framework.

MODEL : The model is responsible for handling all data-related tasks. It can be a table in a
database, a JSON file, or anything else. The model takes the data from where it is stored and
then processes it before sending it to the view. If the model needs to be changed, it is done in
a single place. In a web-based application, the model is the place where data is transformed
from one format to another. For example, let’s say we have a model which receives a dataset
in a particular format and then transforms it into another format, before sending it to the view.
In today’s world, if we want to create any type of website, we must have some sort of
database, because we must accept user input regardless of whether we are creating a simple
blog post. The Model is a component in Django’s architecture that contains the Business
Logic. xThe flow of information is as follows: When you sign up on any website, you click
on a sign up button. When you click on the sign up button, a request is sent to the controller.
Then the controller calls the model and asks it to apply the logic on the form which is
received as a parameter. The model then applies its logic and gives a response to the
controller. The controller then passes the response to you, which is the client.
VIEW :The View component in the Django architecture is used to display the data from the
Model component. It can also be used to collect data from the user and send it to the Model
as a form input. In this way, the View component contains the UI logic. Examples of UI logic
can be found in JavaScript code for animations, visualizations, and other interactive elements.
For example, if you click on a product and then go to the product detail page, the new
webpage that is generated is the product detail view. Similarly, if you click on a category and
then go to the category view, the new webpage that is generated is the category view. You
can replicate the same behavior in your own website by using views.

Controller :Since the controller decides which view to display, it has the power to
manipulate the view’s model. In this way, it can apply any logic and rules to the view’s
model. The controller also determines how to display the view and how to respond to user
input. It can manipulate the view’s model for this purpose as well. Since the view’s model is
an abstraction of the data model, the controller can manipulate the view’s model in any way it
wants. It can also choose not to manipulate the model, but rather display the data as it is. This
is useful in cases where the model’s data is sensitive and must be displayed exactly as it is.
We can say that the controller is the one that decides when and what needs to be displayed.
Controllers are very helpful in keeping our code DRY, maintainable, and scalable. We can
also have more than one controller in a single application. For example, we have a login
controller that deals with the login process and another one that deals with the profile details.

Types of Views

Django views are divided into two major categories:-


 Function-Based Views
 Class-Based Views

Function-Based Views :Function-based views are writer using a function in python which
receives as an argument HttpRequest object and returns an HttpResponse Object. Function-
based views are generally divided into 4 basic strategies, i.e., CRUD (Create, Retrieve,
Update, Delete). CRUD is the base of any framework one is using for development.

Refer to the below articles to get more information on Function-Based views –


 Django CRUD (Create, Retrieve, Update, Delete) Function Based Views
 Create View
 List View
 Detail View
 Update View
 Delete View

Class-Based Views : Class-based views provide an alternative way to implement views as


Python objects instead of functions. They do not replace function-based views, but have
certain differences and advantages when compared to function-based views:
 Organization of code related to specific HTTP methods (GET, POST, etc.) can be
addressed by separate methods instead of conditional branching.
 Object-oriented techniques such as mixins (multiple inheritances) can be used to factor
code into reusable components.
Refer to the below articles to get more information on Class-Based views –
 Class Based Generic Views Django (Create, Retrieve, Update, Delete)
 Createview
 ListView
 DetailView
 UpdateView
 DeleteView
 FormView

With diagram explain working of AJAX.

AJAX communicates with the server using XMLHttpRequest object. Let's try to understand
the flow of ajax or how ajax works by the image displayed below. As you can see in the
above example, XMLHttpRequest object plays a important role.

1. User sends a request from the UI and a javascript call goes to XMLHttpRequest
object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.
Explain REST API and categorize different types.of http requests supported bY REST API.

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


networked applications. It relies on a stateless, client-server communication protocol,
typically HTTP, to access and manipulate resources. Here's an explanation of REST API and
the different types of HTTP requests supported by it:

REST API:

1. Resource-Based: In a RESTful API, resources are the key abstractions. Each resource is
identified by a unique URI (Uniform Resource Identifier), and clients interact with these
resources using standard HTTP methods.

2. Stateless Communication: RESTful APIs are stateless, meaning that each request from a
client to the server contains all the information necessary to process the request. The server
does not store any client state between requests.

3. CRUD Operations: RESTful APIs typically support CRUD (Create, Read, Update, Delete)
operations on resources using HTTP methods (GET, POST, PUT, DELETE). Each HTTP
method corresponds to a specific action on the resource.

4. Representation of Resources: Resources in a RESTful API are represented using a standard


format such as JSON (JavaScript Object Notation) or XML (eXtensible Markup Language).
Clients and servers communicate by exchanging representations of resources.
5. Uniform Interface: RESTful APIs adhere to a uniform interface, which simplifies client-
server interactions. This includes standard methods, resource identifiers (URIs), and media
types for representing resources.

HTTP Methods Supported by REST API:

1. GET: The GET method is used to retrieve a representation of a resource from the server. It
is a safe and idempotent operation, meaning that it does not modify the state of the server and
can be repeated without causing changes.

Example: GET /api/users/123

2. POST: The POST method is used to create a new resource on the server. It typically
involves sending data to the server in the request body, which is used to create the resource.

Example: POST /api/users

Request Body: {"name": "John", "age": 30}

3. PUT: The PUT method is used to update an existing resource on the server. It replaces the
current representation of the resource with the one provided in the request body.

Example: PUT /api/users/123

Request Body: {"name": "John Doe", "age": 31}

4. DELETE: The DELETE method is used to remove a resource from the server. It deletes
the resource identified by the URI provided in the request.

Example: DELETE /api/users/123

5. PATCH: The PATCH method is used to partially update a resource on the server. It applies
partial modifications to the resource specified in the request body.

Example: PATCH /api/users/123

Request Body: {"age": 32}

6. HEAD: The HEAD method is similar to GET but only requests the headers of the
response, not the actual resource representation. It is often used to check the status of a
resource or to retrieve metadata.

Example: HEAD /api/users/123

7. OPTIONS: The OPTIONS method is used to request information about the communication
options available for the target resource. It is commonly used to discover the supported HTTP
methods and other capabilities of a server.

Example: OPTIONS /api/users


Write a short note on Moongoose schema and models.

Mongoose is an elegant MongoDB object modeling tool designed to work in an


asynchronous environment. It provides a straightforward, schema-based solution for
modeling application data and interacting with MongoDB databases. Let's delve into
Mongoose schema and models in detail:

Mongoose Schema:

1. Definition: A Mongoose schema defines the structure of documents within a collection in a


MongoDB database. It specifies the shape of documents, the types of data they contain, and
any validation rules applied to that data.

2. Schema Types: Mongoose provides various schema types to define the data structure of
fields within documents. These include String, Number, Date, Boolean, ObjectId, Array, and
more.

3. Validation: Mongoose schemas allow you to define validation rules for each field, ensuring
that data adheres to specified criteria before being saved to the database. Validation rules can
include required fields, custom validators, min/max values, regular expressions, and more.

4. Default Values: You can specify default values for fields in a schema, which are
automatically assigned to a field if no value is provided during document creation.

5. Nested Schemas: Mongoose supports nesting schemas within other schemas, allowing you
to create complex data structures and relationships between documents.

6. Virtuals: Virtuals are schema properties that are not persisted to the database but are
computed on the fly when accessing documents. They can be useful for deriving values from
other fields or performing calculations.

7. Hooks: Mongoose schemas support pre and post hooks, which are functions that are
executed before or after certain operations, such as saving or querying documents. Hooks can
be used for tasks like data manipulation, validation, or logging.

const mongoose = require('mongoose');

// Define a schema

const userSchema = new mongoose.Schema({

name: {

type: String,

required: true

},

email: {
type: String,

required: true,

unique: true

},

age: {

type: Number,

default: 18

});

// Create a model from the schema

const User = mongoose.model('User', userSchema);

module.exports = User;

Mongoose Models:

1. Model Definition: A Mongoose model is a constructor function that represents a collection


of documents in MongoDB. It acts as an interface for querying and manipulating documents
within that collection.

2. Binding Schema: Each Mongoose model is associated with a Mongoose schema, which
defines the structure of documents stored in the corresponding MongoDB collection.

3. CRUD Operations: Mongoose models provide methods for performing CRUD operations
(Create, Read, Update, Delete) on documents in the associated MongoDB collection. These
methods include `create`, `findOne`, `findById`, `updateOne`, `deleteOne`, and more.

4. Custom Methods: You can define custom instance and static methods on Mongoose
models to encapsulate business logic or perform complex operations related to documents in
the collection.

5. Query Builders: Mongoose models support query builder methods that allow you to
construct and execute MongoDB queries in a fluent and chainable manner. This makes it easy
to build complex queries with multiple conditions and options.

6. Indexes: Mongoose models allow you to define indexes on fields within the associated
MongoDB collection, improving query performance for commonly used fields or queries.
7. Middleware: Mongoose models support middleware functions that can intercept and
modify document operations such as validation, saving, updating, and removing.
Middleware functions can be useful for enforcing business rules, logging, or
triggering additional actions.

const User = require('./userModel');

// Create a new user document

const newUser = new User({

name: 'John Doe',

email: '[email protected]',

age: 25

});

// Save the new user document to the database

newUser.save()

.then(savedUser => {

console.log('User saved:', savedUser);

})

.catch(error => {

console.error('Error saving user:', error);

});

// Query users from the database

User.find({ age: { $gte: 18 } })

.then(users => {

console.log('Users with age greater than or equal to 18:', users);

})

.catch(error => {

console.error('Error querying users:', error);

});
Explain collection, document and.CRUD.operations.in MongoDB.with example.

Collection
Collections are just like tables in relational databases, they also store data, but in the form of
documents. A single database is allowed to store multiple collections.

Schemaless: As we know that MongoDB databases are schemaless. So, it is not necessary in
a collection that the schema of one document is similar to another document. Or in other
words, a single collection contains different types of documents like as shown in the below
example where mystudentData collection contain two different types of documents:

Naming Restrictions for Collection:

Before creating a collection you should first learn about the naming restrictions for
collections:
 Collection name must starts with an underscore or a character.
 Collection name does not contain $, empty string, null character and does not begin with
system. prefix.
 The maximum length of the collection name is 120 bytes(including the database name,
dot separator, and the collection name).

Creating collection: After creating database now we create a collection to store documents.
The collection is created using the following syntax:

db.collection_name.insertOne({..})
Here, insertOne() function is used to store single data in the specified collection. And in the
curly braces {} we store our data or in other words, it is a document.
For Example:
In this example, we create a collection named as the Author and we insert data in it with the
help of insertOne() function. Or in other words, {name: “Ankita”} is a document in the
Author collection, and in this document, the name is the key or field and “Ankita” is the
value of this key or field. After pressing enter we got a message(as shown in the above
image) and this message tells us that the data enters successfully (i.e., “acknowledge”: true)
and also assigns us an automatically created id. It is the special feature provided by
MongoDB that every document provided a unique id and generally, this id is created
automatically, but you are allowed to create your own id (must be unique).
Document
In MongoDB, the data records are stored as BSON documents. Here, BSON stands for binary
representation of JSON documents, although BSON contains more data types as compared to
JSON. The document is created using field-value pairs or key-value pairs and the value of the
field can be of any BSON type.
Syntax:
{
field1: value1
field2: value2
....
fieldN: valueN
}

Naming restriction of fields:

Before moving further first you should learn about the naming restrictions for fields:
 The field names are of strings.
 The _id field name is reserved to use as a primary key. And the value of this field must be
unique, immutable, and can be of any type other than an array.
 The field name cannot contain null characters.
 The top-level field names should not start with a dollar sign ($).
Document Size: The maximum size of the BSON document is 16MB. It ensures that the
single document does not use too much amount of RAM or bandwidth(during transmission).
If a document contains more data than the specified size, then MongoDB provides a GridFS
API to store such type of documents.
Example #2:
Here, the _id field is created by the user. Tip: When you paste data in the functions always
use close parenthesis after pasting the data into the function. If you use close parenthesis
before pasting data in the function, then you will get an error.
MongoDB CRUD operations
As we know that we can use MongoDB for various things like building an application
(including web and mobile), or analysis of data, or an administrator of a MongoDB database,
in all these cases we need to interact with the MongoDB server to perform certain operations
like entering new data into the application, updating data into the application, deleting data
from the application, and reading the data of the application. MongoDB provides a set of
some basic but most essential operations that will help you to easily interact with the
MongoDB server and these operations are known as CRUD operations.

CRUD Operations: CRUD stands for Create, Read, Update, and Delete, which are the basic
operations for managing data in any database. In MongoDB, CRUD operations are performed
using methods provided by the MongoDB driver or MongoDB shell. Here's how each CRUD
operation is performed in MongoDB:

1. Create (Insert): To insert a document into a collection, you can use the `insertOne()` or
`insertMany()` method.
Method Description

It is used to insert a single document in


db.collection.insertOne() the collection.

db.collection.insertMany( It is used to insert multiple documents


) in the collection.

db.createCollection() It is used to create an empty collection


Here's an example:
// Insert a single document into the "users" collection
db.users.insertOne({
name: "John Doe",
age: 30,
email: "[email protected]"
});
// Insert multiple documents into the "users" collection
db.users.insertMany([
{ name: "Alice", age: 25, email: "[email protected]" },
{ name: "Bob", age: 35, email: "[email protected]" }
]);
2. Read (Query): To retrieve documents from a collection, you can use the `find()`
method with optional query criteria.
db.collection.find() It is used to retrieve documents from the collection.
Here's an example:
// Find all documents in the "users" collection
db.users.find();
// Find documents that match a specific criteria
db.users.find({ age: { $gt: 30 } }); // Find users older than 30
```
3. Update: To update documents in a collection, you can use the `updateOne()` or
`updateMany()` method.
Method Description

It is used to update a single document in the collection


db.collection.updateOne() that satisfy the given criteria.

It is used to update multiple documents in the


db.collection.updateMany() collection that satisfy the given criteria.

It is used to replace single document in the collection


db.collection.replaceOne() that satisfy the given criteria.
Here's an example:
// Update a single document in the "users" collection
db.users.updateOne({ name: "John Doe" }, { $set: { age: 31 } });
// Update multiple documents in the "users" collection
db.users.updateMany({ age: { $lt: 30 } }, { $set: { status: "inactive" } });

4. Delete: To delete documents from a collection, you can use the `deleteOne()` or
`deleteMany()` method.
Method Description

It is used to delete a single document from the


db.collection.deleteOne() collection that satisfy the given criteria.

It is used to delete multiple documents from the


db.collection.deleteMany() collection that satisfy the given criteria.
Here's an example:
// Delete a single document from the "users" collection
db.users.deleteOne({ name: "John Doe" });
// Delete multiple documents from the "users" collection
db.users.deleteMany({ status: "inactive" });
3. Explain and create a small program applying flask template
• First, you'll need to install Flask if you haven't already:
pip install Flask
• Now, create a Python script named app.py with the following code:
from flask import Flask, render_template
app = Flask(__name__)
# Dummy list of items
items = ['Apple', 'Banana', 'Orange', 'Mango', 'Pineapple']
@app.route('/')
def index():
return render_template('index.html', items=items)
if __name__ == '__main__':
app.run(debug=True)
• Next, create a directory named templates in the same directory where you have
your app.py file. Inside this templates directory, create a file named index.html with
the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Items List</title>
</head>
<body>
<h1>List of Items</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
• In this HTML file, we're using Jinja2 templating syntax to loop through the items list
passed from the Flask application and display each item in an unordered list (<ul>).
• Now, when you run app.py and navigate to http://127.0.0.1:5000/ in your browser,
you should see a simple webpage displaying the list of items.
• This example demonstrates how Flask templates can be used to render dynamic
content in web applications. You can extend this example by adding more routes
and templates to create more complex web applications.

You might also like