Serverside

Download as pdf or txt
Download as pdf or txt
You are on page 1of 94

Web Technologies

Instructor: Humaira Waqas


Content

• Web Terminologies
• Hypertext Transfer Protocol (HTTP)
• Uniform Resource Locator (URL)
• World Wide Web (WWW)
• World Wide Web (W3C) Consortium
• Evolution of Web
• Internet
• A global computer network, consisting of
interconnected networks using
standardized communication protocols.
• IP Address
• Internet Protocol (IP) Unique address that
identifies a device on the internet or a
local network.
• World Wide Web
• The World Wide Web (WWW) is a system
Web of interlinked hypertext documents
accessed via the Internet. It is
Terminologies an information space where documents
and other web resources are identified
by Uniform Resource Locators (URLs).
• Hyperlink
• In computing, a hyperlink, or simply a link,
is a reference to data that the reader can
directly follow by clicking.
• HTML
• Short for Hypertext Markup Language,
the authoring language used to create
documents on the World Wide Web.
• Markup Language is like a blueprint or
layout for the processing and
appearance of text documents. In
HTML, tags are used to specify the
layout or the way to subsequent line
must appear.
• Web page
• A document on the WWW. Every web
page is identified by a unique URL.
• Website
• A website is a collection of related web
pages, including multimedia content,
Web typically identified with a
common domain name. Each site is
Terminologies owned and managed by an individual,
company or organization.
Web Terminologies
• Home page
• The main page of a Web site. Typically, the home page serves as an
index or table of contents to other documents stored at the site.
• Browser
• Short for Web browser, a software application used to locate and
display Web sites.
• Web server
• A computer that runs websites.
• A computer which has a program install in it that distributes web
pages as they are requested.
• HTTP
• Short for Hyper Text Transfer Protocol, the underlying protocol used by
the WWW.
• HTTP defines how messages are formatted and transmitted, and what
actions Web servers and browsers take in response to various
commands.
Client Server Communication
Http Request
Message
HTTP
• Http Header
• HTTP headers are the code that transfers data between
a Web server and a client.
• HTTP headers are the name or value pairs that are
displayed in the request and response messages of
message headers for Hypertext Transfer Protocol (HTTP)
• Usually, the header name and the value are separated
by a single colon.
• HTTP headers are an integral part of HTTP requests and
responses.
HTTP
• Http Request Header
• Whenever you type a URL into the address bar and try
to access it, your browser sends an HTTP request to the
server.
• The HTTP request header contains information in a
form, e.g.
• Type, capabilities and version of the browser that generates the
request
• Operating system used by the client
• Page that was requested
• Various types of outputs accepted by the browser
HTTP
• Http General Header
• These headers contain directives that need to be
followed, for both the requester and receiver.
• This can include information regarding:
• Caching directives.
• Specified connection options.
• The date
• Upgrade (for if the protocols need to be switched) etc
HTTP
• Http Entity Header
• These headers include information regarding:
• Allow (methods supported by the identified resource)
• Content Encoding.
• Content Language.
• Content Location.
• Content Length.
• MD-5 (for checking the integrity of the message upon
receipt).
• Content Range.
• Content Type.
• When it Expires.
• When it was last modified.
HTTP

• Body is optional.
• Contains data associated with the request like content of an HTML form.
• Body can be divided into two categories:
• Single resource bodies.
• Consist of one single file and is defined by two headers i.e., content-type
and content-length
• Multiple resource bodies.
• Consist of multipart body, each containing different information. This is
typically associated with HTML Forms.
HTTP
• Http Response Header
• Upon receiving the request header, the Web server will
send an HTTP response header back to the client.
• An HTTP response header includes information in a text-
record form that a Web server transmits back to the
client's browser.
• The response header contains particulars such as:
• Type, date and size of the file sent back by the server, as well as
information regarding the server.
Request/ Response Example
• HTTP request to fetch t.html page that does not exist on the web server running on tutorialspoint.com.
• Request Message
• GET /t.html HTTP/1.1
• User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
• Host: www.tutorialspoint.com
• Accept-Language: en-us
• Accept-Encoding: gzip, deflate
• Response Message
• HTTP/1.1 404 Not Found
• Date: Sun, 18 Oct 2012 10:36:20 GMT
• Server: Apache/2.2.14 (Win32)
• Content-Length: 230
• Content-Type: text/html;
• Connection: Closed

<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /t.html was not found on this server.</p>
</body> </html>
Http Response Message
• HTTP/1.1 200 OK
• Date: Mon, 27 Jul 2009 12:28:53 GMT
• Server: Apache/2.2.14 (Win32)
• Content-Type: text/html
• Connection: Closed
• (blank line)
• <html>
• <body>
• <h1>Hello, World!</h1>
• </body>
• </html>
• HTTP is a transaction-oriented client/server
protocol.
HTTP • HTTP is a stateless protocol and creates a TCP
Overview connection for each transaction (e.g., download a
page).
• A stateless protocol is a communications protocol
that treats each request as an independent
transaction that is unrelated to any previous
request.
• Each transaction is treated separately so that the
communication consists of independent pairs of
requests and responses.
• An HTTP server has no knowledge of which web
pages (if any) a client has accessed previously.
• If a web server needs to store a client's state, it can
store cookies in the client’s web browser (cookies
are not part of http).
Web Terminologies
• URI:
• URI stands for Uniform Resource
Identifier and it uniquely identifies a
resource over the Web. • URN:
• URL: URN stands for Uniform Resource Name
• URL stands for Uniform Resource and it identifies a resource by name in a
Locator and it defines the network
location of a specific resource. A given namespace. A namespace refers a
resource, or a web resource refers to group of names or identifiers.
anything ranging from documents,
files, images, web pages, etc. that
can be part of the web architecture.
Web Applications
• Web applications
• A software system that is a combination of Web standards + Web
technologies
• Web Standards
• Produced by the World Wide Web Consortium W3C
• W3C
• An international community that develops standards to ensure
long-term growth of the web.
• A body which provide the standards, specifications, guidelines,
software's and tools to lead the web
• British engineer and computer scientist Tim Berners-Lee, now
Director of the W3C has invented WWW in 1989.
• WWW was unstructured in the beginning.
• HTML 1.0 published in 1991
• HTML 4.01 published in 1999
• not strict, no error generations
• XHTML 1.0, and XHTML 2.0 published in 2000
• Strictly requires to comply by the standards and rejects
web pages otherwise.
• XHTML was rejected by the web developing community
and was abandoned in 2009.
• HTML 5.0 published in 2012
• Often termed as semantic HTML.
• <email>humaira.@abc.com</email>, <nav>link1</nav>
• A way from unstructured data to structure the data to
History facilitate:
of • Search engines to retrieve relevant documents
WWW against keywords.
• Web pages can index appropriately
• Minimization of use of 3rd party audio video players.
• Instead of using 3rd party software's, games,
interactive graphs or drawing tools can be made
using canvas and JavaScript.
Evolution of Web
• Web 1.0
• The era was all about read-only content and static HTML websites.
• Fixed content and primarily informational.
• Limited user interaction (view information).
• Typically, it had simple forms for submitting data
• Web 2.0
• This is about user-generated content and the read-write web.
• Foster two-way communication between users and websites.
• People are consuming as well as contributing information through blogs or sites like
Flickr, YouTube, Digg, etc.
• Web 3.0
• This is about semantic web (or the meaning of data), intelligent search and behavioral
advertising among other things & most of all collective intelligence.
• Data integration and interoperability, allowing different applications to exchange and
interpret data.
• Personalization and context aware experiences, making easier to find relevant
information.
• Use AI and machine learning to facilitate tasks NLP and Knowledge reasoning.
Tiered Architecture
API
• API stands for Application Programming Interface.
An API is a software intermediary that allows two
applications to talk to each other.
• An API is like a waiter in a restaurant. The waiter
takes your order and sends it to the kitchen. The
kitchen then prepares the food and sends it back to
the waiter. The waiter then brings the food to you.
API
FAST API
• FastAPI is a high-performing web framework for
building APIs with Python 3.7+ based on standard
Python type hints.
• It helps developers build applications quickly and
efficiently.
• FastAPI is built on top of the Starlette web server and
includes features that make building web applications
easier, such as:
• automatic data validation
• error handling
• interactive API docs.
FAST API
Features:
• Performance: On par with NodeJS and the Go
language.
• Speed: Increase the development speed 2-3X.
• Easy: Great editor support. Completion everywhere.
Easy to learn and use.
• Robust: Production-ready code with automatic
interactive documentation.
• OpenAPI based: Fully compatible with OpenAPI and
JSON Schema.
FAST API
• Installing FastAPI
FAST API
Creating a simple API
FAST API
uvicorn main:app --reload
FAST API
FASTAPI - Route
• A route is a URL pattern used to direct requests to their
appropriate handlers.
• In web frameworks, a route is typically associated with a
function or method that executes some action, returns
information, or processes data based on the HTTP request.
• Route = path + method
• Path = URI
• Methods:
• POST: to create data.
• GET: to read data.
• PUT: to update data.
• DELETE: to delete data.
• And a few other advanced ones
• FastAPI supports all of the http methods.
FASTAPI

• The @app.get("/") tells FastAPI that the function right below


is in charge of handling requests that go to the path / using a
get operation.
• This is a decorator related to a path operation, or a path
operation decorator.
• To refresh async concept you can read the following article on it.
FASTAPI
path operation
• @app.post()
• @app.put()
• @app.delete()
• @app.options()
• @app.head()
• @app.patch()
• @app.trace()
FASTAPI: Path Parameters

• The value of the path parameter item_id will be passed


to your function as the argument item_id
FAST API
FASTAPI: Path Parameters with types

• In this case, item_id is declared to be an int


• The value of the path parameter item_id will be passed
to your function as the argument item_id
FASTAPI: data validation
FAST API: put fixed paths first
• When creating path
operations, you may find
situations where you have a
fixed path, like /users/me
• also have the path
/users/{user_id} to get data
about a specific user by
some user ID
FASTAPI: query parameters
• http://127.0.0.1:8000/items/?skip=0&limit=10

fake_items_db = [{"item_name": "Foo"}, {"item_name":


"Bar"}, {"item_name": "Baz"}]

@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]

The query is the set of key-value pairs that go after the ? in a


URL, separated by & characters.
FASTAPI: Request Body
• When you need to send data from a client (let's say, a
browser) to your API, you send it as a request body.

• A request body is data sent by the client to your API. A


response body is the data your API sends to the client.

• Your API almost always has to send a response body.


But clients don't necessarily need to send request
bodies all the time.
FASTAPI: Request Body
@app.post("/items/")
async def read_data_body(request: Request):
body = await request.json()
item_id = body.get("item_id")
item_desc = body.get("item_desc")
return {"item_id": item_id, "item_desc":
item_desc}
FASTAPI: Request Body
class Item(BaseModel):
item_id: int
item_desc: str
price: float

@app.post("/items/")
def read_data_body(item: Item):
return {"item id": item.item_id, "item desc":
item.item_desc}
FASTAPI: Request Body
Item is a Pydantic model with three fields:
name (a string)
price (a float)
is_offer (a boolean with a default value of None).

Instances of the Item class will automatically validate input


data against these field definitions.
FASTAPI: Response
• When you create a FastAPI path operation you can normally
return any data from it:
• Dict
• List
• Pydantic model
• database model, etc.
• By default, FastAPI would automatically convert that return
value to JSON using the jsonable_encoder.
• Behind the scenes, it would put that JSON-compatible data
(e.g. a dict) inside of a JSONResponse that would be used to
send the response to the client.
• Note:
In fact, you can return any Response or any sub-class of it.
FASTAPI: Response
• If you want to return a JSONResponse you need to
convert the type to JSON-compatible types e.g a
Pydantic model, Dict etc
• For this purpose, use: jsonable_encoder() to
convert your data before passing it to a response:
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
title: str
timestamp: datetime
description: Union[str, None] = None

app = FastAPI()

@app.put("/items/{id}")
def update_item(id: str, item: Item):
json_compatible_item_data = jsonable_encoder(item)
return JSONResponse(content=json_compatible_item_data)
FASTAPI: Custom Response
from fastapi import FastAPI, Response
app = FastAPI()

@app.get("/legacy/")
def get_legacy_data():
data = """<?xml version="1.0"?>
<shampoo>
<Header> Note:
Apply shampoo here. When you return a Response directly, its data
is not validated, converted (serialized), nor
</Header>
documented automatically.
<Body>
You'll have to use soap here.
</Body>
</shampoo>
"""
return Response(content=data, media_type="application/xml")
FASTAPI: Return Types
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
tags: list[str] = []

@app.post("/items/")
async def create_item(item: Item) -> Item:
return item
FASTAPI: Return Types
class Item(BaseModel):
name: str
description: str | None = None
price: float FastAPI will use this return
type to: Validate the
tax: float | None = None
returned data, It will limit and
tags: list[str] = [] filter the output data to what
is defined in the return type.
@app.get("/items/")
async def read_items() -> list[Item]:
return [
Item(name="Portal Gun", price=42.0),
Item(name="Plumbus", price=32.0),
]
FASTAPI: Form Data
• When you need to receive form fields instead of JSON, you can
use Form.
• To use forms, first install python-multipart
from fastapi import FastAPI, Form

app = FastAPI()
@app.post("/login/")
async def login(username: Annotated[str, Form()], password:
Annotated[str, Form()]):
return {"username": username}

Annotated[str, Form()] is used to specify that the username and password


parameters are expected to be strings obtained from a form submission. It
provides both type information (string) and contextual information (from a
form).
Router
• Router is a crucial component responsible for
directing incoming HTTP requests to the
appropriate handlers based on the request's URL
path and method.
• Purpose of Router:
• Routing Requests
• Organizing Code
• Middleware Integration
• Error Handling
• Enhancing Performance
FASTAPI

• APIRouter is used to create a new router.


• The read_item function is attached to this router.
• The router is then included in the main FastAPI instance.
FASTAPI: main.py
FASTAPI: students.py
FASTAPI: middlewares
• Middleware is a function that runs before and after
each request in your application.
• Middleware is used to perform functions such as
processing requests before passing them to request
handlers, modifying responses before sending them
to clients, handling tasks globally (like logging,
CORS, authentication, etc.), or managing sessions.
FASTAPI: middlewares
Middleware functions in FastAPI can:
• Intercept requests before they reach your
endpoint.
• Intercept responses before they are sent back to
the client.
• Modify requests and/or responses.
• Add or manage custom headers, cookies, or
security mechanisms.
FASTAPI: middlewares
Some common use cases for middleware include:
• Security Headers: Automatically add security headers
to responses.
• Session Management: Manage user sessions across
requests.
• Rate Limiting: Restrict the rate at which user requests
are handled.
• Cross-Origin Resource Sharing (CORS): Define how
resources can be accessed by other domains.
• Logging and Monitoring: Log requests and monitor
response times for APIs.
FASTAPI: middleware example
CORS Middleware
• One of the most common middleware is for
managing Cross-Origin Resource Sharing (CORS),
allowing your API to be safely used from a front-
end running on a different domain or port.
Same origin policy
▪ Same-origin policy is a critical security mechanism that restricts how a
document or script loaded by one origin can interact with a resource
from another origin.
▪ It helps isolate potentially malicious documents, reducing possible attack.
▪ Two URLs have the same origin if the protocol, port (if specified), and
host are the same for both, e.g.
▪ http://store.company.com/dir/page.html
▪ http://store.company.com/dir2/other.html
▪ https://store.company.com/page.html
▪ http://store.company.com:81/dir/page.html
▪ http://news.company.com/dir/page.html
Same origin policy
▪ It prevents a malicious website on the Internet from running JS in a
browser to read data from a third-party service.
▪ It prevents a company intranet (which is protected from direct access by
the attacker by not having a public IP address) and relaying that data to the
attacker.
Cross-origin network access
The same-origin policy controls interactions between two different origins,
such as when you use XMLHttpRequest or an <img> element. These
interactions are typically placed into three categories:
Cross-origin writes are typically allowed. Examples are links, redirects, and
form submissions. Some HTTP requests require preflight.
Cross-origin embedding is typically allowed.
Cross-origin reads are typically disallowed, but read access is often leaked by
embedding, e.g, you can read the dimensions of an embedded image, the
actions of an embedded script, or the availability of an embedded resource
Cross origin network access
• Block cross origin access
• To prevent cross-origin writes, check an unguessable token in the
request CSRF token
• To prevent cross-origin reads of a resource, ensure that it is not
embeddable.
• To prevent cross-origin embeds, ensure that your resource cannot
be interpreted as one of the embeddable formats.
• Allow cross origin access
• Use CORS to allow cross-origin access. CORS is a part of HTTP that
lets servers specify any other hosts from which a browser should
permit loading of content.
cors
• Cross-Origin Resource Sharing (CORS) is an HTTP-header based
mechanism that allows a server to indicate any origins (domain, scheme,
or port) other than its own from which a browser should permit loading
resources.
• CORS also relies on a mechanism by which browsers make a "preflight"
request to the server hosting the cross-origin resource, in order to check
that the server will permit the actual request. In that preflight, the
browser sends headers that indicate the HTTP method and headers that
will be used in the actual request.
• An example of a cross-origin request: the front-end JavaScript code served
from https://domain-a.com uses XMLHttpRequest to make a request for
https://domain-b.com/data.json.
• For security reasons, browsers restrict cross-origin HTTP requests initiated
from scripts.
CORS

• Cross-origin resource sharing (CORS):


• It allows servers to specify not just who can access its assets,
but also how the assets can be accessed.
• Most servers will allow GET requests, meaning they will allow
resources from external origins (say, a web page) to read their
assets.
• HTTP requests methods like PATCH, PUT, or DELETE, however,
may be denied to prevent malicious behavior.
FASTAPI: middleware example
FASTAPI: custom middleware example
FASTAPI: LMS
• Learning Management System (LMS) should handle
courses, users (instructors and students), assignments,
and potentially forums or discussion boards.
• Users (user management Router)
• Courses (course management Router)
• Enrollment (Router)
• Assignment (Router)
• Submission (Router)
• Discussion board (Router)
• Admin (Router)
FASTAPI: LMS
• Users (user management Router)
• /users/register POST
Registers a new user (either a student or an instructor).
• /users/login POST
Authenticates a user and returns a session token or JWT.
• /users/me GET
Retrieves the logged-in user's profile information.
• /users/me PUT
Allows users to update their own profile information.
• /users/me DELETE
Allows a user to delete their account.
FASTAPI: LMS
• Courses (course management Router)
• /course/ POST
Allows instructors to create a new course.
• /course/ GET
Lists all courses, possibly with filtering, sorting, and pagination
capabilities.
• /course/{course_id} GET
Retrieves detailed information about a specific course.
• /course/{course_id} PUT
Allows instructors to update a course's details.
• /courses/{course_id} DELETE
Allows instructors to delete a course.
FASTAPI: LMS
• Enrollment (Router)
• /enrollments/{course_id} POST
Allows students to enroll in a course.
• /enrollments/ GET
Retrieves all courses the logged-in student is enrolled in.
• /enrollments/{course_id} DELETE
Allows a student to unenroll from a course.
FASTAPI: LMS
• Assignment (Router)
• /assignments/{course_id} POST
Allows instructors to create assignments for a course.
• /assignments/{course_id} GET
Lists all assignments for a specific course.
• /assignments/{course_id}/assignment_id} GET
Retrieves details of a specific assignment.
• /assignments/{course_id}/{assignment_id} PUT
Allows instructors to update an assignment.
• /assignments/{course_id}/{assignment_id} DELETE
Allows instructors to delete an assignment.
FASTAPI: LMS
• Submission (Router)
• /submissions/{assignment_id} POST
Allows students to submit assignments.
• /submissions/{assignment_id} GET
Allows instructors to view all submissions for an assignment.
• /submissions/{assignment_id}/{submission_id} GET
Allows instructors to view a specific submission.
• /submissions/{assignment_id}/{submission_id} PUT
Allows instructors to grade or provide feedback on a submission.
FASTAPI: LMS
• Discussion board (Router)
• /discussions/{course_id} POST
Allows users to create a new discussion thread in a course.
• /discussions/{course_id} GET
Lists all discussion threads for a course.
• /discussions/{course_id}/{thread_id}/comments POST
Allows users to comment on a discussion thread.
• /discussions/{course_id}/{thread_id} GET
Retrieves all comments for a specific discussion thread.
FASTAPI: LMS
• Admin (Router)
• /admin/users GET
Lists all users with the option to filter by role (student or
instructor).
• /admin/users/{user_id} DELETE
Admins can delete a user account.
FASTAPI: sessions
• Fast API does not have built-in session
management like some traditional synchronous
web frameworks such as Flask or Django.
• We can implement session management in FastAPI
using various techniques, including:
• Cookies
• JSON Web Tokens (JWT)
• External session management libraries.
FASTAPI: sessions
• In FastAPI, sessions can be managed using various
methods, such as cookies, tokens, or other mechanisms.
• Typically, sessions are used to maintain stateful
information about a user's interactions with a web
application across multiple HTTP requests.
• Sessions can be implemented in FastAPI using cookies:
• Session Handling: FastAPI doesn't have built-in session
management like some other web frameworks. However, you can
implement session management using cookies and
dependencies.
FASTAPI: sessions
• Cookies: You can use HTTP cookies to store session
identifiers or other session-related data on the client side.
• When a user logs in, you can set a session cookie containing a
unique session identifier or some encrypted data.
• This cookie is sent with each subsequent request, allowing the
server to identify the user and retrieve session data as needed.
• Dependencies: You can create a dependency function to
handle session management. This function can extract
session data from cookies, verify session integrity, and
provide session-related information to route handlers.
• Security: Ensure that session data is stored securely and
that sensitive information is properly encrypted to prevent
unauthorized access or tampering.
Every route which needs to be restricted
make a function.
Which checks the username & pwd first
if true then access the route
else
cannot access the route

login---check username & pwd


• If true
set the session id and the information into the cookie
end the response back to the client
Subsequent request
check the session id/ the information which you have already set in
the cookie
If true
send response/ template
Else
redirect to login page
# Example login route to set session cookie
@app.post("/login", response_class=HTMLResponse)
async def login(request: Request, username: str = Form(...),
password: str = Form(...), db = Depends(get_db)):
user = await db.users.find_one({"username": username})
if not user or user["hashed_password"] !=
get_password_hash(password):
return templates.TemplateResponse("login.html", {"request":
request, "error": "Invalid credentials"})
response = RedirectResponse(url="/",
status_code=status.HTTP_303_SEE_OTHER)
session_data = {"user_id": str(user["_id"])}
session_cookie = serializer.dumps(session_data)
response.set_cookie("session", session_cookie)
return response
# Dependency function to handle session
management

async def get_current_user(request: Request):


session_cookie = request.cookies.get("session")
if not session_cookie:
return None
try:
data = serializer.loads(session_cookie)
except BadSignature:
return None
user = await db.users.find_one({"_id": ObjectId(data.get("user_id"))})
if not user:
return None
return user
# Example route that requires session
authentication
@app.get("/secure-route")
async def secure_route(session_data: dict =
Depends(get_session_data)):
if session_data:
# User is logged in, proceed with handling the request
return {"message": "Access granted"}
else:
# User is not logged in, raise Unauthorized exception
raise HTTPException(status_code=401,
detail="Unauthorized")
MongoDb
• MongoDB is a popular NoSQL database that stores data
in JSON-like documents.
• Collection
• A collection is MongoDB is equivalent to a database table.
• Document
• It can be defined as an instance of a MongoDB collection.
• It includes a set of key value pairs.
• All documents include a dynamic schema.
• This means documents within a collection do not need to
have same set of fields and structure.
MongoDb
• Pros
• Schema free database
• Unlike relational databases, it does not follow a typical
schema design.
• It is easy to scale
• Cons It provides less flexibility with querying
MongoDb
• Download and install MongoDB from mongodb.com
• Download community or enterprise edition
• Check by typing mongod -version
• Create a folder-> data, in the drive mongodb is installed on
your computer
• Create db folder in data folder
• Using cmd go to c:/programfiles/mongodb/server/5.0/bin
• run command mongod in the folder
• It will start listening at its default port (27017)
• This means that the server is running
• press ctrl+c and exit
• now run mongo.exe in the same folder. It is the
client connector and start running commands to
create db etc
MongoDb: $regex
• $regex, provides regular expression capabilities for
pattern matching strings in queries. MongoDB uses Perl
compatible regular expressions
• {<field>: { $regex: 'pattern', $options: '<options>' } }
• {<field>: { $regex: /pattern/, $options: '<options>' } }
• $options can be:
•s allow dot character to match all characters
including new line
•i case insensitive match
• m for patterns that include anchors like ^, $
•x capability to ignore all white space characters in
the $regex pattern
Fast API: $regex
async def find_users_by_pattern(pattern):
cursor = db[COLLECTION_NAME].find({
"username": {
"$regex": “john”,
"$options": "i" # Case-insensitive search
}
})
users = await cursor.to_list(length=None)
return users
Fast API: connect to MongoDb
Connect to MongoDB using the Motor library in a FastAPI
application
• pip install motor

# Database settings
MONGODB_URL = "mongodb://localhost:27017"
DATABASE_NAME = "test_db"
COLLECTION_NAME = "users"

# Create a MongoDB client and connect to the database


client = AsyncIOMotorClient(MONGODB_URL)
db = client[DATABASE_NAME]
Fast API: MongoDB aggregation
• MongoDB aggregation operations allow you to
process data records and return computed results.
• Documents enter a multi-stage pipeline
(aggregation pipeline) that can transform the
documents into aggregated results.
• These operations are similar to SQL's GROUP BY,
COUNT, SUM, AVG, etc.
Fast API: MongoDB aggregation pipeline
• Each stage in the pipeline performs an operation on the
input documents and passes the output to the next
stage.
• The stages can include operations like:
• $match: Filters the documents.
• $group: Groups documents by a specified key and
can perform operations on grouped data.
• $project: Reshapes each document, such as
including, excluding fields, or adding new fields.
• $sort: Sorts the documents.
Fast API: MongoDB aggregation pipeline
@app.get("/items/match/{category}")
async def match_items(category: str, db=Depends(get_db)):
pipeline = [
{"$match": {"category": category}}
]
items = await db.aggregate(pipeline).to_list(length=None)
return items

Note:
db.aggregate(pipeline)
The db.aggregate(pipeline) function call is used to execute the
aggregation pipeline on the specified collection.
Fast API: MongoDB aggregation pipeline
pipeline = [
{"$group": {"_id": "$category", "total_price": {"$sum":
"$price"}}}
]
$group: This stage is used to group documents by a
specified field and to perform aggregation operations on
the grouped data.
_id: "$category": This specifies the field by which to group
the documents. In this case, documents are grouped by the
category field.
total_price: {"$sum": "$price"}: This specifies the
aggregation operation to perform on the grouped data.
Here, it calculates the total sum of the price field for each
group of documents.
Categories of Web Application
• Transactional applications
• Workflow based applications
• Project management systems
• Human resource management systems
• Business process management
• Health care management systems
• Collaborative/groupware applications
• Social web applications
• Portal oriented web applications
• Ubiquitous web applications:
• Applications that integrate seamlessly into our daily life.
• There characteristics: context awareness, multi-device support, scalable,
seamless integration etc.
• Examples: Health and fitness app, context-aware social media app, smart
home system, location based services etc
• Web application with respect to usage.
Characteristics of • Usage is heterogenous
Web Applications • Social context
• Web application should be available
24/7
• Web applications may be developed for
known or unknown groups.
• Unknown groups might be disable,
have different customs,
preferences, interests etc.
• Technical context
• Network quality
• Multiplatform delivery
Characteristics of • Web application from development
perspective
Web Applications • Cross-platform compatibility
• Client-server architecture
• Statelessness handling
• Scalability
• Security
• Data management
• Performance optimization
• Testing and debugging
• Continuous Integration and
Continuous Deployment pipeline
automation
References
• https://flatworldbusiness.wordpress.com/flat-
education/previously/web-1-0-vs-web-2-0-vs-web-3-0-a-bird-eye-
on-the-definition/
• https://www.business2community.com/tech-gadgets/eras-of-the-
web-web-0-0-through-web-5-0-02239654
• https://www.researchgate.net/publication/321366810_Concept_
and_Dimensions_of_Web_40
• https://www.w3.org/
• https://www.w3.org/WAI/fundamentals/accessibility-intro/

You might also like