SDF - Supporting - Reference Material
SDF - Supporting - Reference Material
Full-stack developers are often responsible for the entire web application
development process, from start to finish, which means they must have a strong
understanding of all the technologies and tools involved in web development. They
also need to work effectively with others on a team, as web development is typically
a collaborative process.
Most full-stack developers have a firm foundation in web development technologies,
such as HTML, CSS, and JavaScript. They also have experience with server-side
technologies such as PHP, Ruby on Rails, and Node.js. In addition to their technical
skills, full-stack developers also deeply understand how the various parts of a website
or application work together.
------------------------------------------------------------------------------------------------------------------
1
(MR23-1CS0103) Stack Development Frameworks Unit_01
2
(MR23-1CS0103) Stack Development Frameworks Unit_01
Superior Scalability
Full-stack development has the added advantage of enhancing the scalability of
an organization’s applications.
Scalability is essential because it enables businesses to manage higher loads or
traffic without requiring costly program modifications.
By increasing the scalability of their apps, businesses may ensure that they can
continue to satisfy their customers’ needs even as they expand.
Full-stack development can enhance scalability by providing a robust and
versatile architecture.
With this type of development, adding new features and capabilities to your
system as needed is simple.
Enhanced Speed to Market
Another significant advantage of full-stack development is that it expedites
product launches for businesses. That said, this particular aspect can prove out be
advantageous for enterprises operating in a competitive market, allowing them to
launch their items before their competitors.
Moreover, full-stack development can cut the amount of time spent on
development initiatives by enterprises.
This can free up time and resources for firms to concentrate on other aspects of
their operations.
Enhanced Client Satisfaction
Full-stack development can assist firms in developing more user-friendly and
customer-centric applications.
Consequently, organizations that implement full stack development will have a
major competitive edge in terms of consumer experience.
Quick Solutions to Errors
Occasionally, during the creation of an application, things do not function
properly, possibly due to a coding error. Having said that, this process can be
handled fast because a full-stack developer is familiar with the arrangement of
programs and can easily discover errors.
Easy Updates and Maintenance
Developing apps using full-stack technology enables a developer to issue updates
based on customer requirements simply.
As they are involved in both the frontend and backend of the application, they are
familiar with the codes. They can optimize them when the app requires updates
and the code demands an additional feature accessible on the web and mobile
application.
3
(MR23-1CS0103) Stack Development Frameworks Unit_01
1. HTML
HTML stands for Hypertext Markup Language. It is used to design the front-end
portion of web pages using a markup language. HTML is a combination of Hypertext
and Markup language.
Hyper Text: HyperText simply means "Text within Text." A text has a link within it,
is a hypertext. Whenever you click on a link which brings you to a new webpage, you
have clicked on a hypertext. HyperText is a way to link two or more web pages
(HTML documents) with each other.
Markup language: A markup language is a computer language that is used to apply
layout and formatting conventions to a text document. Markup language makes text
more interactive and dynamic. It can turn text into images, tables, links, etc.
4
(MR23-1CS0103) Stack Development Frameworks Unit_01
Web Page: A web page is a document which is commonly written in HTML and
translated by a web browser. A web page can be identified by entering an URL. A
Web page can be of the static or dynamic type. With the help of HTML only, we can
create static web pages.
Features of HTML
It is a very easy and simple language. It can be easily understood and modified.
It is very easy to make an effective presentation with HTML because it has a lot of
formatting tags.
It is a markup language, so it provides a flexible way to design web pages along with
the text.
It facilitates programmers to add a link on the web pages (by html anchor tag), so it
enhances the interest of browsing of the user.
It is platform-independent because it can be displayed on any platform like Windows,
Linux, and Macintosh, etc.
It facilitates the programmer to add Graphics, Videos, and Sound to the web pages
which makes it more attractive and interactive.
HTML is a case-insensitive language, which means we can use tags either in lower-
case or upper-case.
2. CSS
CSS stands for Cascading Style Sheets. It is a style sheet language which is used to
describe the look and formatting of a document written in markup language. It
provides an additional feature to HTML. It is generally used with HTML to change
the style of web pages and user interfaces. It can also be used with any kind of XML
documents including plain XML, SVG and XUL.
CSS is used along with HTML and JavaScript in most websites to create user interfaces
for web applications and user interfaces for many mobile applications.
Advantages of CSS
CSS saves time − You can write CSS once and then reuse the same sheet in multiple
HTML pages. You can define a style for each HTML element and apply it to as many
Web pages as you want.
Easy maintenance − To make a global change, simply change the style, and all
elements in all the web pages will be updated automatically.
Global web standards − Now HTML attributes are being deprecated and it is being
recommended to use CSS. So it's a good idea to start using CSS in all the HTML pages
to make them compatible with future browsers.
Platform Independence − The Script offer consistent platform independence and can
support latest browsers as well.
3. JavaScript
JavaScript is a dynamic computer programming language.
5
(MR23-1CS0103) Stack Development Frameworks Unit_01
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be
included in or referenced by an HTML document for the code to be interpreted by the
browser.
It means that a web page need not be a static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the
entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
Less server interaction − It validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors
Increased interactivity – It is used to create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
Richer interfaces − JavaScript used to include such items as drag-and-drop
components and sliders to give a Rich Interface to the website visitors.
6
(MR23-1CS0103) Stack Development Frameworks Unit_01
Testing: Angular JS is designed in a way that we can test right from the start. So, it
is very easy to test any of its components through unit testing and end-to-end
testing.
Model View Controller: In Angular JS, it is very easy to develop application in a
clean MVC way. You just have to split your application code into MVC components
i.e. Model, View and the Controller.
2. React.js
React is a declarative, efficient, and flexible JavaScript library for building user
interfaces. ReactJS is an open-source, component-based front-end library
responsible only for the view layer of the application. It is maintained by
Facebook. Moreover, React Js makes Front-end development very easy.
Advantages of ReactJS:
Composable: We can divide these codes and put them in custom components. Then
we can utilize those components and integrate them into one place.
Declarative: In react the DOM is declarative. We can make interactive UIs by
changing the state of the component and React takes care of updating the DOM
according to it.
SEO Friendly: React affects the SEO by giving you a SPA (Single Page Application)
which requires Javascript to show the content on the page which can be rendered
and indexed.
Community: React has a huge community because of it’s demand each company
wants to work with React. Companies like Meta, Netflix, etc built on React.
Easy to learn: HTML-like syntax of JSX make you comfortable with the codes of
React, it only requires to need a basic knowledge of HTML, CSS, and JS
fundamentals to start working with it.
3. Bootstrap
Bootstrap is a free and open-source tool collection for creating responsive websites
and web applications. It is the most popular HTML, CSS, and JavaScript framework
for developing responsive, mobile-first websites.
Advantages of Bootstrap
It is Faster and Easier way for Web-Development.
It creates Platform-independent web-pages.
It creates Responsive Web-pages.
It designs responsive web pages for mobile devices too.
It is a free and open-source framework
Bootstrap is compatible with all modern browsers (Chrome, Firefox, Internet
Explorer, Edge, Safari, and Opera).
4. jQuery
jQuery is an open-source JavaScript library that simplifies the interactions between
an HTML/CSS document, or more precisely the Document Object Model (DOM),
7
(MR23-1CS0103) Stack Development Frameworks Unit_01
The back-end portion is built by using some languages which are discussed
below:
1. PHP
PHP is an acronym for "PHP: Hypertext Preprocessor".
PHP is a server-side scripting language, which is used to manage the dynamic
content of the website.
Since PHP code is executed on the server side, it is called a server-side scripting
language.
PHP is an object-oriented language also it can be embedded into HTML.
8
(MR23-1CS0103) Stack Development Frameworks Unit_01
PHP can handle the forms, such as - collect the data from users using forms, save it
into the database, and return useful information to the user. For example -
Registration form.
Features of PHP
PHP is very popular language because of its simplicity and open source. There are some
important features of PHP given below:
Performance: PHP script is executed much faster than those scripts which are
written in other languages such as JSP and ASP. PHP uses its own memory, so the
server workload and loading time is automatically reduced, which results in faster
processing speed and better performance.
Open Source: PHP source code and software are freely available on the web. You
can develop all the versions of PHP according to your requirement without paying
any cost. All its components are free to download and use.
Familiarity with syntax: PHP has easily understandable syntax. Programmers are
comfortable coding with it.
Embedded: PHP code can be easily embedded within HTML tags and script.
Platform Independent: PHP is available for WINDOWS, MAC, LINUX & UNIX
operating system. A PHP application developed in one OS can be easily executed in
other OS also.
Database Support: PHP supports all the leading databases such as MySQL, SQLite,
ODBC, etc.
Error Reporting: PHP has predefined error reporting constants to generate an error
notice or warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language: PHP allows us to use a variable without declaring its
datatype. It will be taken automatically at the time of execution based on the type of
data it contains on its value.
Web servers Support: PHP is compatible with almost all local servers used today
like Apache, Netscape, Microsoft IIS, etc.
Security: PHP is a secure language to develop the website. It consists of multiple
layers of security to prevent threads and malicious attacks.
Control: Different programming languages require long script or code, whereas
PHP can do the same work in a few lines of code. It has maximum control over the
websites like you can make changes easily whenever you want.
2. Java:
Java is one of the most popular and widely used programming languages and
platforms. It is highly scalable.
Features of Java
Platform Independent: Compiler converts source code to bytecode and then the
JVM executes the bytecode generated by the compiler. This bytecode can run on any
platform be it Windows, Linux, or macOS which means if we compile a program on
Windows, then we can run it on Linux and vice versa.
9
(MR23-1CS0103) Stack Development Frameworks Unit_01
3. Python:
Python is a very popular general-purpose interpreted, interactive, object-oriented,
and high-level programming language.
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building
large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
10
(MR23-1CS0103) Stack Development Frameworks Unit_01
Advantages of python
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the users to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable − Low-level modules can be added to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than
shell scripting.
4. Node.js:
Node.js is a very powerful JavaScript-based platform built on Google Chrome's
JavaScript V8 Engine.
It is used to develop I/O intensive web applications like video streaming sites,
single-page applications, and other web applications.
Node.js is open source, completely free, and used by thousands of developers
around the world.
Features of Node.js
Easy Scalability: Node JS is built upon Chrome V8’s engine powered by Google. It
allows Node to provide a server-side runtime environment that compiles and
executes JavaScript at lightning speeds.
Fast Suite: Being built on Google Chrome's V8 JavaScript Engine, Node.js library is
very fast in code execution. It provides microservice architectures in which the
applications are breaking down into isolated and independent services.
No Buffering: Node.js applications never buffer any data. These applications simply
output the data in chunks.
Data Streaming: NodeJS comes to the rescue since it’s good at handling such an I/O
process which allows users to transcode media files simultaneously while they are
being uploaded. It takes less time compared to other data processing methods for
processing data.
11
(MR23-1CS0103) Stack Development Frameworks Unit_01
Back-End Frameworks:
1. Express :
Express is a Nodejs framework used for backend/server-side development.
Express.js is a small framework that works on top of Node.js web server
functionality to simplify its APIs and add helpful new features.
It makes it easier to organize your application’s functionality with middleware and
routing. It adds helpful utilities to Node.js HTTP objects and facilitates the rendering
of dynamic HTTP objects.
It is used to build single-page, multi-page, and hybrid web applications. With its
help, you can handle multiple different HTTP requests.
2. Django:
Django is a Python web-based framework, following the model-template-views
pattern. It is used to build large and complex web applications.
Django emphasizes reusability of components
Its features include being fast, secure, and scalable.
Django follows the MVT design pattern (Model View Template).
Model - The data you want to present, usually data from a database.
View - A request handler that returns the relevant template and content - based
on the request from the user.
Template - A text file (like an HTML file) containing the layout of the web page,
with logic on how to display the data.
3. Ruby on Rails:
Ruby on Rails or also known as rails is a server-side web application development
framework that is written in the Ruby programming language.
It supports MVC(model-view-controller) architecture that provides a default
structure for database, web pages, and web services, it also uses web standards like
JSON or XML for transfer data and HTML, CSS, and JavaScript for the user interface.
The usage of different well-known web development patterns and frameworks, such
as:
Don’t Repeat Yourself (DRY): It is a software development philosophy that seeks
to minimize the repeating of data or codes.
Convention Over Configuration (CoC): It offers a variety of viewpoints on the best
ways to carry out certain tasks in a web-based application.
12
(MR23-1CS0103) Stack Development Frameworks Unit_01
The application programs using the client-server architecture should follow the given
below strategies:
Client
A client is a program that runs on the local machine requesting service from the
server. A client program is a finite program means that the service started by the
user and terminates when the service is completed.
Server
A server is a program that runs on the remote machine providing services to the
clients. When the client requests for a service, then the server opens the door for the
incoming requests, but it never initiates the service.
A server program is an infinite program means that when it starts, it runs infinitely
unless the problem arises. The server waits for the incoming requests from the
clients. When the request arrives at the server, then it responds to the request.
13
(MR23-1CS0103) Stack Development Frameworks Unit_01
2. File servers
File servers act as a centralized location for files. One of the daily life examples to
understand this is the files that we store in Google Docs. The cloud services for Microsoft
Office and Google Docs can be accessed from your devices; the files that you save from
your computer can be accessed from your phone. So, the centrally stored files can be
accessed by multiple users.
3. Web servers
Web servers are high-performance computers that host different websites. The server
site data is requested by the client through high-speed internet.
Workstations
Workstations are also called client computers. Workstations work as subordinates to
servers and send them requests to access shared files and databases. A server requests
information from the workstation and performs several functions as a central repository
of files, programs, databases, and management policies. Workstations are governed by
server-defined policies.
Servers
Servers are defined as fast-processing devices that act as centralized repositories of
network files, programs, databases, and policies. Servers have huge storage space and
robust memory to deal with multiple requests, approaching simultaneously from various
workstations. Servers can perform many roles, such as mail server, database server, file
server, and domain controller, in client-server architecture at the same time.
Networking devices
Now that we know about the roles that workstations and servers play, let us learn about
what connects them, networking devices. Networking devices are a medium that
connects workstations and servers in a client-server architecture. Many networking
devices are used to perform various operations across the network. For example, a hub
is used for connecting a server to various workstations. Repeaters are used to effectively
transfer data between two devices. Bridges are used to isolate network segmentation.
14
(MR23-1CS0103) Stack Development Frameworks Unit_01
to the server via a network. After processing, the consumer gets the final data per the
submitted request.
When a user puts in any file or website’s URL, the browser sends this request to the
Domain Name System (DNS) server.
The DNS server looks for the web server’s address.
The DNS server replies with the IP address of the web server.
The browser sends HTTPS or HTTP requests to the IP address of the web server.
The server sends the required files for the website.
The browser provides the files, and you have the website displayed. The rendering is
completed with the help of a CSS interpreter, DOM interpreter and JS Engine.
15
(MR23-1CS0103) Stack Development Frameworks Unit_01
---------------------------------------------------------------------------------------------------------------------
Stack Frameworks
A stack framework is a software framework that provides a basic structure for web
applications. It typically includes a web server, database, and programming language.
16
(MR23-1CS0103) Stack Development Frameworks Unit_01
The web server handles requests from clients while the database stores data. The
programming language is used to build the web application.
Stack frameworks are popular because they can be used to develop complex applications
quickly. They can also be easily extended to add new features. However, stack
frameworks can be difficult to learn and use and can be inflexible if the application needs
to be customized.
MEAN Stack
The MEAN stack is a JavaScript-based framework for developing web applications.
MEAN is named after MongoDB, Express, Angular, and Node, the four key technologies
that make up the layers of the stack.
This stack leads to faster development as well as the deployment of the Web Application.
Angular is Frontend Development Framework whereas Node.js, Express, and MongoDB
are used for Backend development.
17
(MR23-1CS0103) Stack Development Frameworks Unit_01
After that, the request moves to NodeJS which will parse the request.
ExpressJs will make calls to MongoDB to get or set data.
MongoDB will retrieve the requested data and return that request to the Express JS
NodeJS will return the request to the client.
At the client side, AngularJS to display the result fetched from MongoDB.
MongoDB
MongoDB is the database used in web development. It is a NoSQL database, and a
NoSQL database can be defined as a non-relational and document-oriented database
management system. As it is a document-oriented database management system, so it
stores the data in the form of documents. The SQL databases use SQL query language to
query the database, whereas the MongoDB is a NoSQL database that uses BSON
language to query the database. JSON is a text-based format, but it is inefficient in terms
of speed and space. In order to make MongoDB efficient in terms of space and speed,
BSON was invented. BSON basically stores the JSON format in the binary form that
optimizes the space, speed, and complexity.
Mongo DB is an ideal choice for a database system where you need to manage large sized
tables with millions of data. Moreover, including a field to Mongo DB is easier as it does
not require updating the entire table. With Mongo DB you develop an entire application
with just one application, i.e. JavaScript.
Express.js
Express is a mature, flexible, lightweight server framework. It is designed for building
single, multi-page, and hybrid web applications. This lightweight framework uses the
Pug engine to provide support for templates.
Advantages of Express.js
It is simple and lightweight software. It is not heavy to get installed in the machine
and make the application running.
It is easy to customize and configure as we can see it provides the flexibility that we
require.
It is a better choice for creating the API as when the application requires various APIs
to communicate with different people then the Express.js is a good option
Angular.js
Angular JS is an open-source JavaScript framework. Angular is maintained by
Google. The goal of this framework is to introduce MVC (Model View Controller)
architecture in the browser-based application that makes the development and testing
process easier. The framework helps the user create a smarter web app that supports
personalization.
AngularJS allows us to use HTML as a template language. Therefore, user can extend
HTML’s syntax to express the components of application.
18
(MR23-1CS0103) Stack Development Frameworks Unit_01
Advantages of Angular.js
It is a two-way data binding which means that it keeps the model and view in sync. If
any changes are made in the model, then automatically view will also be updated
accordingly.
The Angular.js is designed with testing in mind. The components of angular.js
application can be tested with both the testing, such as unit testing and end to end
testing.
With the help of Angular.js, it is easy to develop the application in an MVC
architecture.
Node.js
Node.js is an open-source platform and provides a runtime environment for executing
the javascript code. It is mainly used for building the back-end application.
Since there are two types of apps, such as web apps and mobile apps, where web apps
run on the browser and mobile apps run on mobile devices. Both web app and mobile
app are the client apps to which the user interacts.
These apps require to communicate with the backend services to store the data, send
emails, push notifications.
Node.js is an ideal platform to build highly scalable, data-intensive, and real-time
applications. It can be used for agile development and highly-scalable services. For
example, PayPal is a java and spring-based application using Node.js.
Advantages of Node.js
The node.js applications are faster than the other framework-based applications and
require fewer people to build the app.
It requires fewer lines of code.
The Node app has a 35% faster response time than the other apps.
The major advantage of using node.js is that node.js uses javascript. If you are a front-
end developer, then you can easily transit from the front-end to the full stack
developer.
Advantages of MeanStack
Simple and fast: MeanStack is simple to use and fast as it allows the programmers to
write the code in a single language for both the server and client-side.
Universal coding is possible in MeanStack: In MeanStack, the code written in one
framework can be easily transferred to another framework.
Highly flexible: Once the development process of an application is completed, it is
easier to test the application on the cloud platform.
Cost-effective: Since the mean stack uses single language, i.e., javascript so a smaller
number of developers required to develop the app using mean stack.
Open source: All the technologies used in the mean stack are open-source and
available for free.
---------------------------------------------------------------------------------------------------------------------
19
(MR23-1CS0103) Stack Development Frameworks Unit_01
MERN Stack
MERN Stack is a collection of powerful technologies and robust, used to develop scalable
master web applications comprising backend, front-end, and database components. It is
JavaScript that is used for the faster and easier development of full-stack web
applications. MERN Stack is a technology that is a user-friendly full-stack JavaScript
framework for building applications and dynamic websites.
MERN Stack consists of four main components or can say four main technologies:
1. MongoDB
MongoDB ( Database ), mainly used for preparing document database and is a NoSQL
(Non-Structured Query Language ) Database System
The term 'NoSQL' typically means a non-relational database that does not require a
fixed schema or proper relational tables to store the necessary data in it. MongoDB
stores the data in a different format other than the relational tables, consisting of rows
and columns.
It implies that MongoDB is not based on the table-like relational database structure.
On the other hand, it provides an altogether different mechanism for the retrieval and
storage of data.
The storage format in which the data is stored is known as BSON, which stands for
Binary JavaScript Object Notation; its binary structure encodes length and type of
information, which allows it to be parsed much more quickly.
It allows a highly scalable and flexible document structure.
It is very faster as compared to RDBMS due to its efficient storage and indexing
techniques.
In MongoDB, complex join operations are not available; hence, it cannot support
complex transactions.
MongoDB uses JavaScript for coding as a language which is one of the great
advantages.
It is Schemaless as any data stored which is stored in a separate document.
It also supports a flexible document model, which is very fast for any developer to
create.
MongoDB is a NoSQL database that scales by adding more and more servers and
increases productivity with its flexible document model.
2. Express
Express, mainly used for developing Node.js web framework also it is a JavaScript
server-side framework that runs within js.
It provides the developer with a platform to create and maintain robust servers.
Express is used for building and designing web and mobile applications easily and
quickly.
Express is used to provide server-side logic for mobile and web applications, and as
such, it is used all over the place.
20
(MR23-1CS0103) Stack Development Frameworks Unit_01
3. React
React, mainly used for developing a client-side JavaScript framework
Before using react, it has some prerequisites that one should follow, that you must
download Node packages in your system with their latest versions. Also, you must
have an understanding of HTML, CSS and JavaScript.
It is used to build user interfaces, especially for a single page web application.
It is not a JavaScript framework. It is just a JavaScript library developed by Facebook
to solve problems we could not solve earlier using other libraries while building web
and mobile applications.
React is also used for making a grip over the view layer for mobile and web
applications.
It allows us to create reusable UI (User Interface) components also it is very fast,
simple and scalable.
It allows developers to create large web applications that can easily change the data
of the page even without reloading the page.
The main objective of reacting is that it only works on user interfaces in the
application, whether mobile or web.
React is also used with a combination of other JavaScript libraries or frameworks.
4. Node.js
Node.js, mainly used for developing the premier JavaScript web server
js is an open-source server environment, and it is a cross-platform runtime
environment for executing JavaScript code outside a browser.
js is not a programming language, and even it is not a framework.
It is often used for building and developing numerous backend services like net
applications, mobile applications.
It will run on numerous operative systems like Windows, Mac, Linux, Unix, etc.
It is incredibly simple to urge started with it and may even be used for agile
development and prototyping also it provides quick services to the users.
21
(MR23-1CS0103) Stack Development Frameworks Unit_01
Server or middle-tier - It is just next level from the top layer and is mainly handled by
two components of the MERN stack, i.e., Express.js and Node.js. These two's components
handle it simultaneously because Express.js maintained the Server-side framework,
running inside the Node.js server. Express.js is one of the widely used backend
development JavaScript Frameworks. It allows developers to spin up robust APIs
(Application Programming Interface) and web servers much easier and simpler. It also
adds helpful functionalities to Node.js HTTP (HyperText Transfer Protocol) objects.
Whereas on the other hand, Node.js plays a very important role in itself. It is an open-
source server environment, and it is a cross-platform runtime environment for executing
JavaScript code outside a browser. Node.js continuously uses JavaScript; thus, it's
ultimately helpful for a computer user to quickly create any net service or any net or
mobile application.
Database as backend tier - It is one of the most important levels of the MERN Stack and
is mainly handled by MongoDB; the main role of a database is to store all the data related
to your application, for example - content, statistics, information, user profiles, comments
22
(MR23-1CS0103) Stack Development Frameworks Unit_01
and so on. It mainly stores all the data for safety purposes. It maintains a proper record,
which usually returns the data to the user whenever required. It mainly stores the data
in the database. It generates two or more replica files of the data so that whenever the
system fails, it can retrieve the exact information or data that the user wanted earlier. It
implies that MongoDB is not based on the table-like relational database structure. On the
other hand, it provides an altogether different mechanism for the retrieval and storage of
data. Mongo DB is the most popular NoSQL (NoSQL or Non Structured Query
Language) database, an open-source document-oriented database. The term 'NoSQL'
typically means a non-relational database that does not require a fixed schema or proper
relational tables to store the necessary data in it. MongoDB stores the data in a different
format other than the relational tables, consisting of rows and columns.
23
(MR23-1CS0103) Stack Development Frameworks Unit_01
MongoDB
MongoDB is an open-source document NoSQL database. NoSQL database systems
offer an alternative to traditional relational databases using SQL (Structured Query
Language). The data is stored in tables, rows, and columns in a relational database,
with relationships between entities. Whereas, in NoSQL databases such as MongoDB,
the data is represented in a JSON-like structure which is stored in documents.
NoSQL Databases store data in an unstructured format and process non-similar data
sets that are associated with each other. Therefore, it has fewer restrictions and more
flexibility with the use of dissimilar fields within a collection as compared to relational
databases.
MongoDB Atlas used for a fully-managed cloud database for full-scale applications
and mongoose npm library can connect the database with our backend.
ExpressJS
A framework layered on top of NodeJS, used to build the backend of a site using
NodeJS functions and structures.
Express is a Node.js web application framework that provides a range of features for
building web applications and APIs. It makes it easy to create and manage routes,
handle requests and responses, and more.
NodeJS
Node.js is a JavaScript runtime environment that allows developers to create server-side
applications using JavaScript. Node.js is used for building the backend of the MEVN
stack. It is a highly scalable, non-blocking I/O platform that makes it ideal for real-time
applications.
VueJS
VueJS is a highly flexible, lightweight open-source JavaScript Framework used for
building single-page web applications, i.e while shifting between different routes, the
website won’t require a reload.
VueJS is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to
design the user interface layer, it is easy to pick up for any developers. It is compatible
with other libraries and extensions as well. In the development field, there may be so
many issues that cannot be solved by using a single library, so the VueJS is compatible
with other libraries. The VueJS is supported by all popular browsers like Chrome,
Firefox, IE, Safari, etc.
VueJS uses a two-way binding model which makes it very easy to update app data
and browser view. It is developer friendly framework, i.e it is easier to learn as it
allows both HTML and .jsx syntax and also has detailed documentation to refer to
and learn.
24
(MR23-1CS0103) Stack Development Frameworks Unit_01
2. Apache:
The second layer consists of web server software, typically Apache Web Server. This
layer resides on top of the Linux layer.
25
(MR23-1CS0103) Stack Development Frameworks Unit_01
Apache HTTP Server is a free web server software package made available under an
open-source license. It used to be known as Apache Web Server when it was created
in 1995.
It offers a secure and extendable Web server that's in sync with current HTTP
standards. Web servers are responsible for translating from web browsers to their
correct website.
3. MySQL:
MySQL is a relational database management system used to store application data. It
is an open-source and keeps all the data in a format that can easily be queried with
the SQL language.
SQL works great with well-structured business domains, and a great workhorse that
can handle even the most extensive and most complicated websites with ease.
MySQL stores details that can be queried by scripting to construct a website. MySQL
usually sits on top of the Linux layer alongside Apache. In high-end configurations,
MySQL can be offloaded to a separate host server.
4. PHP:
The scripting layer consists of PHP and other similar web programming languages.
The PHP open-source scripting language works with Apache to create dynamic web
pages. We cannot use HTML to perform dynamic processes such as pulling data out
of a database.
To provide this type of functionality, we drop PHP code into the parts of a page that
you want to be dynamic. Websites and Web Applications run within this layer.
PHP is designed for efficiency. It makes programming easier and allowing to write
new code, hit refresh, and immediately see the resulting changes without the need for
compiling.
LAMP Architecture
LAMP has classic layered architecture, with Linux at the lowest level. The next layer
is Apache and MySQL, followed by PHP.
Although PHP is at the top or presentation layer, the PHP component sits inside
Apache.
26
(MR23-1CS0103) Stack Development Frameworks Unit_01
The LAMP stack order of execution shows how the elements interoperate. The process
starts when the Apache webserver receives requests for web pages from a user's
browser. If the request is for a PHP file, Apache passes the request to PHP, which
loads the file and executes the code contained in the file. PHP also communicates with
MySQL to fetch any data referenced in the code.
PHP then uses the code in the file and the data from the database to create
the HTML that browsers require to display web pages. The LAMP stack is efficient at
handling not only static web pages but also dynamic pages where the content may
change each time it is loaded depending on the date, time, user identity and other
factors.
After running the file code, PHP then passes the resulting data back to the Apache
webserver to send to the browser. It can also store this new data in MySQL. And of
course, all of these operations are enabled by the Linux operating system running at
the base of the stack.
Features of LAMP
1. Efficiency
LAMP will minimize production time since it is an open-source stack usable for a
decade. We are willing to draw on and make things easier for those in the past.
Function in an Apache module that can configure the last 20 percent to 80 percent and
save tremendous time.
2. Flexibility
Though LAMP uses Linux as an OS, other modules of an alternative OS may be
used to satisfy those specifications. There is, for instance, a Microsoft Windows
WAMP stack.
LAMP is open source and non-proprietary so we can avoid lock-in. We have the
flexibility to select the right components for specific projects or business
requirements.
LAMP offers flexibility in other ways as well. Apache is modular in design, and
we will find there are existing, customizable modules available for many different
extensions. These modules range from support for other languages to
authentication capabilities.
Advantages of LAMP
LAMP has the following advantages, such as:
The LAMP stack consists of four components, all of which are examples of Free and
Open-Source Software (FOSS). As they are free and available for download, it attracts
the attention of many users who wish to avoid paying large sums of money when
developing their website.
Because it is FOSS, the source code of the software is shared and available for people
to make changes and improvements, enhancing its overall performance.
The LAMP stack has proven to be a secure and stable platform thanks to its vast
community that contributes when any problems arise.
27
(MR23-1CS0103) Stack Development Frameworks Unit_01
We can easily customize the stack and interchange the components with other open-
source software to suit the needs.
LAMP is its secure architecture and well-established encryption practices that have
been proven in the enterprise.
---------------------------------------------------------------------------------------------------------------------
Rails or Ruby on Rails
Ruby on Rails or also known as rails is a server-side web application development
framework that is written in the Ruby programming language.
It supports MVC(model-view-controller) architecture that provides a default
structure for database, web pages, and web services, it also uses web standards like
JSON or XML for transfer data and HTML, CSS, and JavaScript for the user interface.
The usage of different well-known web development patterns and frameworks, such
as:
Don’t Repeat Yourself (DRY): It is a software development philosophy that seeks
to minimize the repeating of data or codes.
Convention Over Configuration (CoC): It offers a variety of viewpoints on the best
ways to carry out certain tasks in a web-based application.
MVC architecture
The MVC architecture helps to separate the different components of the application,
making it easier to understand, maintain, and improve. For example, if the user need to
change the way the data is displayed, they can make the changes in the view without
affecting the model or the controller. This makes the development process smoother and
more efficient.
28
(MR23-1CS0103) Stack Development Frameworks Unit_01
interactions, such as submitting forms and communicates with the model to update the
data.
29
(MR23-1CS0103) Stack Development Frameworks Unit_01
Django
Django is a Python framework that makes it easier to create web sites using Python.
Django emphasizes reusability of components, also referred to as DRY (Don't Repeat
Yourself), and comes with ready-to-use features like login system, database
connection and CRUD operations (Create Read Update Delete).
Django follows the MVT design pattern (Model View Template).
Model
View
Template
Model
The model provides data from the database.
In Django, the data is delivered as an Object Relational Mapping (ORM), which is a
technique designed to make it easier to work with databases.
The most common way to extract data from a database is SQL. One problem with SQL
is that you have to have a pretty good understanding of the database structure to be
able to work with it.
Django, with ORM, makes it easier to communicate with the database, without having
to write complex SQL statements.
View
A request handler that returns the relevant template and content - based on the
request from the user.
A view is a function or method that takes http requests as arguments, imports the
relevant model(s), and finds out what data to send to the template, and returns the
final result.
Template
A text file (like an HTML file) containing the layout of the web page, with logic on
how to display the data.
The Template is a presentation layer which handles User Interface part completely.
A template consists of static parts of the desired HTML output as well as some special
syntax describing how dynamic content will be inserted.
30
(MR23-1CS0103) Stack Development Frameworks Unit_01
If URL maps, a view is called that interact with model and template, it renders a
template.
Django responds back to the user and sends a template as a response.
Features of Django
Rapid Development: Django was designed with the intention to make a framework
which takes less time to build web application. The project implementation phase is a
very time taken but Django creates it rapidly.
Secure: Django takes security seriously and helps developers to avoid many common
security mistakes, such as SQL injection, cross-site scripting, cross-site request forgery
etc. Its user authentication system provides a secure way to manage user accounts and
passwords.
Scalable: Django is scalable in nature and has ability to quickly and flexibly switch
from small to large scale application project.
Fully loaded: Django includes various helping task modules and libraries which can
be used to handle common Web development tasks. Django takes care of user
authentication, content administration, site maps, RSS feeds etc.
Versatile: Django is versatile in nature which allows it to build applications for
different-different domains. Now a days, Companies are using Django to build
various types of applications like: content management systems, social networks sites
or scientific computing platforms etc.
Open Source: Django is an open source web application framework. It is publicly
available without cost. It can be downloaded with source code from the public
repository. Open source reduces the total cost of the application development.
Vast and Supported Community: Django is a one of the most popular web
framework. It has widely supportive community and channels to share and connect.
---------------------------------------------------------------------------------------------------------------------
31
(MR23-1CS0103) Stack Development Frameworks Unit_02
What is Database?
The database is a collection of inter-related data which is used to retrieve, insert and
delete the data efficiently. It is also used to organize the data in the form of a table,
schema, views, and reports, etc.
For example: The college Database organizes the data about the admin, staff, students
and faculty etc.
What is DBMS?
Database management system is a software which is used to manage the database.
It consists of a group of programs which manipulate the database.
DBMS provides an interface to perform various operations like database creation,
storing data in it, updating data, creating a table in the database.
It provides protection and security to the database. In the case of multiple users, it
also maintains data consistency.
Characteristics of DBMS
Real-world entity: Modern DBMS are more realistic and uses real world entities to
design its architecture. It uses the behavior and attributes too. For example, a school
database may use student as entity and their age as their attribute.
Relation-based tables: DBMS allows entities and relations among them to form as
tables. This eases the concept of data saving. A user can understand the architecture
of database just by looking at table names etc.
Isolation of data and application: A database system is entirely different than its data.
Where database is said to active entity, data is said to be passive one on which the
database works and organizes. DBMS also stores metadata which is data about data,
to ease its own process.
Less redundancy: DBMS follows rules of normalization, which splits a relation when
any of its attributes is having redundancy in values. Following normalization, which
itself is a mathematically rich and scientific process, make the entire database to
contain as less redundancy as possible.
Consistency: DBMS always enjoy the state on consistency where the previous form
of data storing applications like file processing does not guarantee this. Consistency
1
(MR23-1CS0103) Stack Development Frameworks Unit_02
is a state where every relation in database remains consistent. There exist methods
and techniques, which can detect attempt of leaving database in inconsistent state.
Query Language: DBMS is equipped with query language, which makes it more
efficient to retrieve and manipulate data. A user can apply as many and different
filtering options, as he or she wants. Traditionally it was not possible where file-
processing system was used.
ACID Properties: DBMS follows the concepts for ACID properties, which stands for
Atomicity, Consistency, Isolation and Durability. These concepts are applied on
transactions, which manipulate data in database. ACID properties maintains database
in healthy state in multi-transactional environment and in case of failure.
Multiuser and Concurrent Access: DBMS support multi-user environment and
allows them to access and manipulate data in parallel. Though there are restrictions
on transactions when they attempt to handle same data item, but users are always
unaware of them.
Multiple views: DBMS offers multiples views for different users. A user who is in
sales department will have a different view of database than a person working in
production department. This enables user to have a concentrate view of database
according to their requirements.
Security:
o The Database should be accessible to the users in a limited way.
o The access to make changes to a database by the user should be limited, and
the users must not be given complete access to the entire Database.
o Unauthorized users should not be allowed to access the Database.
o Authentication: The DBMS has authentication for various users that directly
refers to the limit to which the user can access the Database.
Advantages of DBMS
Redundancy problem can be solved.
Has a very high security level.
Presence of Data integrity.
Support multiple users.
Avoidance of inconsistency.
Shared data
Any unauthorized access is restricted
Provide backup of data
Disadvantages of DBMS
Complexity
Size
Performance
Higher impact of a failure
Cost of DBMS
---------------------------------------------------------------------------------------------------------------------
2
(MR23-1CS0103) Stack Development Frameworks Unit_02
3
(MR23-1CS0103) Stack Development Frameworks Unit_02
It doesn't offer backup and recovery of DBMS system provides backup and
data if it is lost. recovery of data even if it is lost.
There is no efficient query processing in You can easily query data in a database
the file system. using the SQL language.
These system doesn't offer concurrency. DBMS system provides a concurrency
facility.
---------------------------------------------------------------------------------------------------------------------
Database Schema
A database schema is a logical representation of data that shows how the data in a
database should be stored logically. It shows how the data is organized and the
relationship between the tables.
Database schema contains table, field, views and relation between different keys like
primary key, foreign key.
Data are stored in the form of files which is unstructured in nature which makes
accessing the data difficult. Thus to resolve the issue the data are organized in
structured way with the help of database schema.
Database schema provides the organization of data and the relationship between the
stored data.
Database schema defines a set of guidelines that control the database along with that
it provides information about the way of accessing and modifying the data.
There are three levels of the database schema are defined according to the three levels of
data abstraction.
o Data Abstraction refers to the process of hiding irrelevant details from the user.
Levels of the schema
Physical Schema
Logical Schema
View Schema
4
(MR23-1CS0103) Stack Development Frameworks Unit_02
The physical level is used to describe complex low-level data structures in detail.
The internal level is generally is concerned with the following activities:
Storage space allocations.
For Example: B-Trees, Hashing etc.
Access paths.
For Example: Specification of primary and secondary keys, indexes, pointers
and sequencing.
Data compression and encryption techniques.
Optimization of internal structures.
Representation of stored fields.
5
(MR23-1CS0103) Stack Development Frameworks Unit_02
Any change made will be absorbed by the mapping between external and conceptual
levels.
6
(MR23-1CS0103) Stack Development Frameworks Unit_02
7
(MR23-1CS0103) Stack Development Frameworks Unit_02
The DBMS supports concurrency and crash recovery by carefully scheduling user
requests and maintaining a log of all changes to the database.
DBMS components associated with concurrency control and recovery include the
transaction manager, which ensures that transactions request and release locks
according to a suitable locking protocol and schedules the execution transactions;
The lock manager, which keeps track of requests for locks and grants locks on
database objects when they become available; and the recovery manager, which is
responsible for maintaining a log and restoring the system to a consistent state after a
crash.
The disk space manager, buffer manager, and file and access method layers must
interact with these components.
---------------------------------------------------------------------------------------------------------------------
8
(MR23-1CS0103) Stack Development Frameworks Unit_02
Database Models
Data models define how the logical structure of a database is modeled. Data Models are
fundamental entities to introduce abstraction in a DBMS. Data models define how data
is connected to each other and how they are processed and stored inside the system.
The very first data model could be flat data-models, where all the data used are to be kept
in the same plane. Earlier data models were not so scientific, hence they were prone to
introduce lots of duplication and update anomalies.
1. Hierarchical Model
The hierarchical database model organizes data into a tree-like structure, with a single
root, to which all the other data is linked.
The hierarchy starts from the Root data, and expands like a tree, adding child nodes
to the parent nodes.
In this model, a child node will only have a single parent node.
This model efficiently describes many real-world relationships like the index of a
book, etc.
IBM's Information Management System (IMS) is based on this model.
Data is organized into a tree-like structure with a one-to-many relationship between
two different types of data, for example, one department can have many courses,
many teachers, and of course many students(like shown in the diagram below).
9
(MR23-1CS0103) Stack Development Frameworks Unit_02
2. Network Model
The Network Model is an extension of the Hierarchical model.
In this model, data is organized more like a graph, and allowed to have more than
one parent node.
In the network database model, data is more related as more relationships are
established in this database model.
As the data is more related, hence accessing the data is also easier and fast.
This database model uses many-to-many data relationships.
Integrated Data Store (IDS) is based on this database model.
The implementation of the Network model is complex, and it's very difficult to
maintain it.
The Network model is difficult to modify also.
3. Entity-relationship Model
In this database model, relationships are created by dividing objects of interest into
entities and their characteristics into attributes.
Different entities are related using relationships.
ER Models are defined to represent the relationships in pictorial form to make it easier
for different stakeholders to understand.
This model is good to design a database, which can then be turned into tables in a
relational model.
Let's take an example, if we have to design a School Database, then the Student will
be an entity with attributes name, age, address, etc. As an Address is generally
complex, it can be another entity with attributes street, pincode, city, etc, and there
will be a relationship between them.
10
(MR23-1CS0103) Stack Development Frameworks Unit_02
4. Relational Model
In this model, data is organized in two-dimensional tables and the relationship is
maintained by storing a common field.
This model was introduced by E.F Codd in 1970, and since then it has been the most
widely used database model, infact, we can say the only database model used around
the world.
The basic structure of data in the relational model is tables. All the information related
to a particular type is stored in rows of that table.
Hence, tables are also known as relations in relational model.
5. Object-oriented Model
In this model, data is stored in the form of objects.
11
(MR23-1CS0103) Stack Development Frameworks Unit_02
6. NoSQL Model
The NoSQL database model supports an unstructured style of storing data.
Data is stored as documents.
The documents look more like JSON strings or Key-value based object
representations.
It provides a flexible schema.
It does provide features like indexing, relationships between data, etc.
The support for data querying is limited in the NoSQL database model.
This database model is well-suited for Big data applications, real-time analytics, CMS
(Content Management systems), etc.
7. Graph Model
The Graph database model is based on more real-world like relationships.
Data is represented using Nodes or entities.
The nodes are related using edges.
The popular database Neo4j is based on the Graph database model.
12
(MR23-1CS0103) Stack Development Frameworks Unit_02
If your application has simple data requirements, then you should not use the graph
database model.
In modern applications like social networks, recommendation systems, etc. the
graph database model is well-suited.
RDBMS Terminology
Attribute: Each column in a Table. Attributes are the properties which define a
relation. e.g., Student_Rollno, NAME,etc.
Tables: In the Relational model the, relations are saved in the table format. It is stored
along with its entities. A table has two properties rows and columns. Rows represent
records and columns represent attributes.
Tuple: It is nothing but a single row of a table, which contains a single record.
Relation Schema: A relation schema represents the name of the relation with its
attributes.
Degree: The total number of attributes which in the relation is called the degree of the
relation.
Cardinality: Total number of rows present in the Table.
Column: The column represents the set of values for a specific attribute.
13
(MR23-1CS0103) Stack Development Frameworks Unit_02
Relation instance: Relation instance is a finite set of tuples in the RDBMS system.
Relation instances never have duplicate tuples.
Relation key: Every row has one, two or multiple attributes, which is called relation
key.
Attribute domain: Every attribute has some pre-defined value and scope which is
known as attribute domain.
RDBMS Keys
KEYS in DBMS is an attribute or set of attributes which helps you to identify a row (tuple)
in a relation (table). They allow you to find the relation between two tables. Keys help
you uniquely identify a row in a table by a combination of one or more columns in that
table. Key is also helpful for finding unique record or row from the table. Database key
is also helpful for finding unique record or row from the table.
14
(MR23-1CS0103) Stack Development Frameworks Unit_02
Candidate Key: A set of attributes that uniquely identify tuples in a table. Candidate
Key is a super key with no repeated attributes.
Alternate Key: A column or group of columns in a table that uniquely identify every
row in that table.
Foreign Key: A column that creates a relationship between two tables. The purpose
of foreign keys is to maintain data integrity and allow navigation between two
different instances of an entity.
Compound Key: Two or more attributes that allow you to uniquely recognize a
specific record. It is possible that each column may not be unique by itself within the
database.
Integrity Constraints
Integrity constraints are rules that help to maintain the accuracy and consistency of data
in a database.
Integrity constraints ensure that the data insertion, updating, and other processes have
to be performed in such a way that data integrity is not affected.
Integrity constraints can also be used to enforce relationships between tables.
1. Key Constraint
Keys are the entity set that is used to identify an entity within its entity set uniquely.
An entity set can have multiple keys, but out of which one key will be the primary
key. A primary key can contain a unique and null value in the relational table.
2. Domain Constraint
Domain constraint defines the domain or set of values for an attribute.
It specifies that the value taken by the attribute must be the atomic value from its
domain.
The data type of domain includes string, character, integer, time, date, currency, etc.
The value of the attribute must be available in the corresponding domain
15
(MR23-1CS0103) Stack Development Frameworks Unit_02
---------------------------------------------------------------------------------------------------------------------
16
(MR23-1CS0103) Stack Development Frameworks Unit_02
SQL
SQL stands for Structured Query Language. It is used for storing and managing data
in relational database management system (RDMS).
It is a standard language for Relational Database System. It enables a user to create,
read, update and delete relational databases and tables.
All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as
their standard database language.
DDL
Data Definition Language (DDL) or Schema Definition Language, statements are used to
define the database structure or schema.
These statements handle the design and storage of database objects.
CREATE
CREATE DATABASE:
The CREATE DATABASE statement is used to create a new SQL database.
Syntax
CREATE DATABASE databasename;
Example
The following SQL statement creates a database called "testDB":
CREATE TABLE:
The CREATE TABLE statement is used to create a new table in a database.
Syntax
CREATE TABLE table_name (column1 datatype, column2 datatype,
column3 datatype, .... );
The column parameters specify the names of the columns of the table.
17
(MR23-1CS0103) Stack Development Frameworks Unit_02
The datatype parameter specifies the type of data the column can hold (e.g. varchar,
integer, date, etc.).
Example
The following example creates a table called "Persons" that contains five columns: PersonID,
LastName, FirstName, Address, and City:
CREATE TABLE Persons (PersonID int, LastName varchar(255),
FirstName varchar(255), Address varchar(255),City varchar(255));
Describe Persons;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| PersonID | int | YES | | NULL | |
| LastName | varchar(255)| YES | | NULL | |
| Firstname| varchar(255)| YES | | NULL | |
| Address | varchar(255)| YES | | NULL | |
| City | varchar(25) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
Field indicates the column name, Type is the data type for the column, NULL indicates
whether the column can contain NULL values, Key indicates whether the column is indexed,
and Default specifies the column's default value. Extra displays special information about
columns:
ALTER TABLE:
The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
18
(MR23-1CS0103) Stack Development Frameworks Unit_02
Example:
RENAME TABLE persons to students_info;
TRUNCATE:
It is used to delete all the rows from the table and free the space containing the table.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE Persons;
19
(MR23-1CS0103) Stack Development Frameworks Unit_02
Syntax
DROP TABLE table_name;
Example
The following SQL statement drops the existing table "Person": DROP TABLE Person;
---------------------------------------------------------------------------------------------------------------------
DML
The SQL commands that deals with the manipulation of data present in the database belong
to DML or Data Manipulation Language and this includes most of the SQL statements.
DML is responsible for all forms data modification in a database.
INSERT:
The insert statement is used to add new row to a table.
Syntax
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);
Or
INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);
Example
Insert the values into the following table (person).
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| ID | int | NO | | NULL | |
| NAME | varchar(20) | YES | | NULL | |
| AGE | int | YES | | NULL | |
| ADDRESS | varchar(20) | YES | | NULL | |
| SALARY | int | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
UPDATE
UPDATE Query is used to modify the existing records in a table. The WHERE clause with
the UPDATE query to update the selected rows, otherwise all the rows would be affected.
Syntax
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Example
Update the ADDRESS for a customer whose ID number is 5 in the table.
20
(MR23-1CS0103) Stack Development Frameworks Unit_02
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | ram | 32 | Chennai | 2000 |
| 2 | sam | 28 | Hyd | 2500 |
| 3 | Henry | 30 | Bangalore | 5000 |
| 4 | Adam | 29 | Pune | 6500 |
| 5 | Alice | 25 | LONDON | 8500 |
+----+----------+-----+-----------+----------+
To modify all the ADDRESS and the SALARY column values in the CUSTOMERS table, not
need to use the WHERE clause as the UPDATE query would be enough as shown in the
following code block.
UPDATE person SET ADDRESS = “LONDON” , SALARY = 5000;
DELETE
DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise
all the records would be deleted.
Syntax
DELETE FROM table_name
WHERE [condition];
Example
The following code has a query, which will DELETE a customer, whose ID is 5.
21
(MR23-1CS0103) Stack Development Frameworks Unit_02
To DELETE all the records from the CUSTOMERS table, no need to use the WHERE clause
and the DELETE query would be as follows –
DELETE FROM person;
---------------------------------------------------------------------------------------------------------------------
DQL
SELECT:
SELECT statement is used to fetch the data from a database table which returns this data in the
form of a result table. These result tables are called result-sets.
Syntax
SELECT column1, column2, columnN FROM table_name;
Example
To fetch all the fields of the table,
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | ram | 32 | Chennai | 2000 |
| 2 | sam | 28 | Hyd | 2500 |
| 3 | Henry | 30 | Bangalore | 5000 |
| 4 | Adam | 29 | Pune | 6500 |
| 5 | Alice | 25 | Delhi | 8500 |
+----+----------+-----+-----------+----------+
+----+----------+
| ID | NAME |
+----+----------+
| 1 | ram |
| 2 | sam |
| 3 | Henry |
| 4 | Adam |
| 5 | Alice |
+----+----------+
---------------------------------------------------------------------------------------------------------------------
TCL
TCL stands for Transaction control language.
TCL commands help the user manage the transactions that take place in a database.
COMMIT. ROLLBACK and SAVEPOINT are the most commonly used TCL
commands in SQL.
22
(MR23-1CS0103) Stack Development Frameworks Unit_02
COMMIT
COMMIT command in SQL is used to save all the transaction-related changes
permanently to the disk.
Syntax: COMMIT
;
Auto-commit
• Auto-commit mode means that when a statement is completed, the method
commit is called on that statement automatically.
• Turn off/on the auto-commit using the SET autocommit statement.
SAVEPOINT
Savepoint helps to save the transaction temporarily.
The SAVEPOINT statement is used to set a save point for the transaction with the
specified name.
The changes done till savpoint will be unchanged and all the transactions after
savepoint will be rolled back.
RELEASE SAVEPOINT
The RELEASE SAVEPOINT statement deletes the specified savepoint.
ROLLBACK
Rollback is used to restore the database to that state which was last committed.
Syntax: ROLLBACK;
---------------------------------------------------------------------------------------------------------------------
23
(MR23-1CS0103) Stack Development Frameworks Unit_02
DCL
• Data control language (DCL) is used to access the stored data. It helps in controlling
access to information stored in a database.
• It provides the administrators, to remove and set database permissions to desired
users as needed.
• These commands are employed to grant, remove and deny permissions to users for
retrieving and manipulating a database.
• The different DCL commands are GRANT & REVOKE.
GRANT
It is employed to grant a privilege to a user.
GRANT command allows specified users to perform specified tasks.
The privilege names are SELECT, UPDATE, DELETE, INSERT, ALTER, ALL.
Natural Join
Natural join is an SQL join operation that creates a join on the base of the common
columns in the tables. To perform natural join there must be one common attribute
(Column) between two tables. Natural join will retrieve from multiple relations.
SELECT [column_names | *]
FROM table_name1
NATURAL JOIN table_name2;
Self-Join
Self-Join is used to join a table to itself. This means that each row in a table is joined to
itself and every other row in that table. However, referencing the same table more than
once within a single query will result in an error. To avoid this, SQL SELF JOIN aliases
are used.
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
Cross Join
An SQL Cross Join is a basic type of inner join that is used to retrieve the Cartesian
product (or cross product) of two individual tables. That means, this join will combine
each row of the first table with each row of second table (i.e. permutations).
SELECT column_name(s)
FROM table1
CROSS JOIN table2;
Outer Join
SQL Outer joins give both matched and unmatched rows of data depending on the
type of outer joins. These types are outer joins are sub-divided into the following types:
Left Outer Join:
The SQL LEFT JOIN joins two tables based on a common column. It selects records
that have matching values in these columns and the remaining rows from the left table.
SELECT column-name(s)
FROM table1 LEFT OUTER JOIN table2
ON table1.column-name = table2.column-name;
Right Outer Join
The SQL RIGHT JOIN statement joins two tables based on a common column. It
selects records that have matching values in these columns and the remaining rows from
the right table.
SELECT columns_from_both_tables
FROM table1
RIGHT JOIN table2 25
ON table1.column1 = table2.column2
(MR23-1CS0103) Stack Development Frameworks Unit_02
CREATE TRIGGER
Create a trigger in SQL Server by using the CREATE TRIGGER statement as follows:
26
(MR23-1CS0103) Stack Development Frameworks Unit_02
Where,
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger
would fire. This clause is valid only for row-level triggers.
Types of Triggers
There are three types of Triggers:
Level Triggers
Event Triggers
Timing Triggers
Level Triggers
Level triggers are divided into two parts:
Event Triggers
Event triggers are divided into three parts:
27
(MR23-1CS0103) Stack Development Frameworks Unit_02
Timing Triggers
Timing triggers are divided into two parts:
Before Trigger
It fires before the DML statement is executed.
After Trigger
It fires after the DML statement has been executed.
Benefits of Triggers
Triggers can be written for the following purposes −
Generating some derived column values automatically
Enforcing referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions
---------------------------------------------------------------------------------------------------------------------
Index
SQL Indexes are special lookup tables that are used to speed up the process of data
retrieval.
They hold pointers that refer to the data stored in a database, which makes it easier
to locate the required data records in a database table.
SQL Indexes work similar to the index of a book or a journal.
SQL Indexes need their own storage space within the database. Despite that, the
users cannot view them physically as they are just performance tools.
CREATE INDEX
An index in SQL can be created using the CREATE INDEX statement. This
statement allows you to name the index, to specify the table and which column or
columns to index, and to indicate whether the index is in an ascending or
descending order.
28
(MR23-1CS0103) Stack Development Frameworks Unit_02
Syntax
The basic syntax of a CREATE INDEX is as follows −
CREATE INDEX index_name ON table_name;
Rename an INDEX
ALTER INDEX old_Index_Name RENAME TO new_Index_Name;
Remove an INDEX
DROP INDEX Index_Name;
Types of Indexes
There are various types of indexes that can be created using the CREATE INDEX
statement. They are:
Unique Index
Single-Column Index
Composite Index
Implicit Index
Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A
unique index does not allow any duplicate values to be inserted into the table. It is
automatically created by PRIMARY and UNIQUE constraints when they are applied
on a database table, in order to prevent the user from inserting duplicate values into
the indexed table column(s). The basic syntax is as follows.
CREATE UNIQUE INDEX index_name on table_name (column_name);
Single-Column Indexes
A single-column index is created only on one table column. The syntax is as follows.
Composite Indexes
A composite index is an index that can be created on two or more columns of a table.
Its basic syntax is as follows.
29
(MR23-1CS0103) Stack Development Frameworks Unit_02
Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server
when an object is created. For example, indexes are automatically created when
primary key and unique constraints are created on a table in MySQL database.
---------------------------------------------------------------------------------------------------------------------
Views
A view is a virtual or logical table that allows to view or manipulate parts of the tables.
A view can contain all rows of a table or select rows from a table. A view can be created
from one or many tables which depends on the written SQL query to create a view.
Views allow users to do the following −
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data in such a way that a user can see and (sometimes) modify
exactly what they need and no more.
Summarize data from various tables which can be used to generate reports.
Creating Views
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables or another view.
The basic CREATE VIEW syntax is as follows −
UPDATE view_name
SET column1 = value1, column2 = value2....,
columnN = valueN
WHERE [condition];
30
(MR23-1CS0103) Stack Development Frameworks Unit_02
Uses of a View: A good database should contain views due to the given reasons:
1. Restricting data access – Views provide an additional level of table security by
restricting access to a predetermined set of rows and columns of a table.
2. Hiding data complexity – A view can hide the complexity that exists in multiple
tables join.
3. Simplify commands for the user – Views allow the user to select information from
multiple tables without requiring the users to actually know how to perform a join.
4. Store complex queries – Views can be used to store complex queries.
5. Multiple view facility – Different views can be created on the same table for
different users.
---------------------------------------------------------------------------------------------------------------------
Review Questions
31
(MR23-1CS0103) Stack Development Frameworks Unit_03
Django Architecture
Django web framework follows the MVT (Model View Template) architecture.
This architectural pattern is designed for easy and rapid web development.
Model
The model provides data from the database.
In Django, the data is delivered as an Object Relational Mapping (ORM), which is a
technique designed to make it easier to work with databases.
The most common way to extract data from a database is SQL. One problem with
SQL is that you have to have a pretty good understanding of the database structure
to be able to work with it.
Django, with ORM, makes it easier to communicate with the database, without
having to write complex SQL statements.
View
A request handler that returns the relevant template and content - based on the
request from the user.
A view is a function or method that takes http requests as arguments, imports the
relevant model(s), and finds out what data to send to the template, and returns the
final result.
Template
A text file (like an HTML file) containing the layout of the web page, with logic on
how to display the data.
1
(MR23-1CS0103) Stack Development Frameworks Unit_03
The Template is a presentation layer which handles User Interface part completely.
A template consists of static parts of the desired HTML output as well as some
special syntax describing how dynamic content will be inserted.
--------------------------------------------------------------------
Features of Django
Rapid Development: Django was designed with the intention to make a framework
which takes less time to build web application. The project implementation phase is
a very time taken but Django creates it rapidly.
Secure: Django takes security seriously and helps developers to avoid many
common security mistakes, such as SQL injection, cross-site scripting, cross-site
request forgery etc. Its user authentication system provides a secure way to manage
user accounts and passwords.
Scalable: Django is scalable in nature and has ability to quickly and flexibly switch
from small to large scale application project.
Fully loaded: Django includes various helping task modules and libraries which can
be used to handle common Web development tasks. Django takes care of user
authentication, content administration, site maps, RSS feeds etc.
Versatile: Django is versatile in nature which allows it to build applications for
different-different domains. Now a days, Companies are using Django to build
various types of applications like: content management systems, social networks
sites or scientific computing platforms etc.
2
(MR23-1CS0103) Stack Development Frameworks Unit_03
3
(MR23-1CS0103) Stack Development Frameworks Unit_03
application server updates the hosted files before sending content to your
browser via the HTTP server.
4
(MR23-1CS0103) Stack Development Frameworks Unit_03
Select Directory and then give a name to our project and then Click on Create.
Open the terminal in pycharm and type the following command to install Django
pip install django
This command fetches the django package from the Python Package Index (PyPI)
using pip. After the installation has completed, you can pin your dependencies to
make sure that you’re keeping track of which Django version you installed:
Type the following Command in pycharm Terminal to check the Django version.
python -m django –version
5
(MR23-1CS0103) Stack Development Frameworks Unit_03
--------------------------------------------------------------------
Django Hello World Application
Step 1: Open PyCharm and Click on Create New Project.
Step 2: Select Directory and then give a name to our project and then Click on Create.
Step 3: Then Check if Django is installed or not in your Computer.
Type the following Command in pycharm Terminal located at Bottom Left.:
python -m django --version
If it is Already installed then we can see the Django version installed in our
Computer.
6
(MR23-1CS0103) Stack Development Frameworks Unit_03
def myview(request):
return HttpResponse("Hello world!")
urlpatterns = [
path("",myview, name="home"),
]
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("polls.urls")),
]
--------------------------------------------------------------------
A view function, or “view” for short, is simply a Python function that takes a web
request and returns a web response. This response can be the HTML contents of a Web
page, or a redirect, or a 404 error, or an XML document, or an image, etc.
def myview(request):
text = """<h1>welcome to my app !</h1>"""
return HttpResponse(text)
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("myapp.urls")),
]
Django already has mentioned a URL here for the admin. The path function takes the
first argument as a route of string or regex type.
8
(MR23-1CS0103) Stack Development Frameworks Unit_03
urlpatterns = [
path('', myview),
]
When a user makes a request for a page on your web app, Django controller takes
over to look for the corresponding view via the url.py file, and then return the
HTML response or a 404 not found error, if not found.
In url.py, the most important thing is the "urlpatterns" tuple. It’s where you define
the mapping between URLs and views.
Create a template folder inside the project directory, and create a HTML file named
myfirst.html.
Open the HTML file and insert the following:
9
(MR23-1CS0103) Stack Development Frameworks Unit_03
<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<p>Welcome to my first Django project!</p>
</body>
</html>
Open the views.py file and replace the view with the following updates
from django.http import HttpResponse
from django.template import loader
def myview(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
10
(MR23-1CS0103) Stack Development Frameworks Unit_03
--------------------------------------------------------------------
Rendering dynamic content in templates
Django has Template System for Display Content on Web.
Using Views and Django Template we can display data in the template.
There are lots of Django Template Tags and Filter for displaying data dynamically.
We can pass the Model data to view for rendering it in the template.
Here the context dictionary will be key- value pairs that are passed to the template
being rendered as variables. Each key becomes the variable name in the template, and
you can access the value in the template by referencing the key name. The snippet
below populates the context variable with some dynamic data.
views.py
from django.shortcuts import render
def myview(request):
cname = 'Python'
duration = '4 Months'
seats = 5
course_details = {'nm': cname, 'du': duration, 'st':
seats}
return render(request,'course.html',course_details)
Variables in Django Templates are referenced using the special syntax of two curly
braces, followed by the variable name, followed by two additional curly braces.
It looks like this:
{{ variable }}
This is not standard HTML but is picked up by Django as it parses and evaluates the
template file. When the template engine finds a variable, it evaluates that variable
and replaces it with the value contained in the context.
11
(MR23-1CS0103) Stack Development Frameworks Unit_03
The result is that we now have dynamic data getting loaded into the template for each
page view.
--------------------------------------------------------------------
Template inheritance
Template inheritance allows you to build a base “skeleton” template that contains all
the common elements of your site and defines blocks that child templates can override.
Let’s look at template inheritance by starting with an example:
12
(MR23-1CS0103) Stack Development Frameworks Unit_03
First, create a view function that renders the templates. In this case, you will render the
base.html template. Import the render method from Django shortcuts. Then create a
view function named index that returns and renders the index template.
Views.py
from django.shortcuts import render
def myview(request):
template = loader.get_template('child.html')
return HttpResponse(template.render())
base.html
<html>
<!DOCTYPE html>
<html>
<body>
<h1>Hello All</h1>
<p>Welcome to my blog</p>
{% block mymessage %}
{% endblock %}
</body>
</html>
This template, which we’ll call base.html, defines an HTML skeleton document that
you might use for a two-column page. It’s the job of “child” templates to fill the
empty blocks with content.
In this example, the block tag defines three blocks that child templates can fill in. All
the block tag does is to tell the template engine that a child template may override
those portions of the template.
A child template might look like this:
{% extends 'base.html' %}
{% block mymessage %}
<p>This page has a master page</p>
{% endblock %}
13
(MR23-1CS0103) Stack Development Frameworks Unit_03
The “extends” tag is the key here. It tells the template engine that this template
“extends” another template. When the template system evaluates this template, first
it locates the parent – in this case, “base.html”.
At that point, the template engine will notice the three block tags in base.html and
replace those blocks with the contents of the child template. Depending on the value
of blog_entries, the output might look like:
--------------------------------------------------------------------
DRY (don't repeat yourself) principle
The DRY (don't repeat yourself) principle is a best practice in software development
that recommends software engineers to do something once, and only once.
According to the DRY principle, every discrete chunk of knowledge should have
one, unambiguous, authoritative representation within a system. The goal of the
DRY principle is to lower technical debt by eliminating redundancies in process and
logic whenever possible.
Redundancies in process
To prevent redundancies in processes (actions required to achieve a result),
followers of the DRY principle seek to ensure that there is only one way to complete
a particular process. Automating the steps wherever possible also reduces
redundancy, as well as the number of actions required to complete a task.
Redundancies in logic
To prevent redundancies in logic (code), followers of the DRY principle use
abstraction to minimize repetition. Abstraction is the process of removing
characteristics until only the most essential characteristics remain.
14
(MR23-1CS0103) Stack Development Frameworks Unit_03
In Django, DRY stands for "Don't Repeat Yourself," which is a software development
principle that promotes code reuse and reduces duplication. The DRY principle
emphasizes the importance of writing modular, reusable code and avoiding
repetition wherever possible.
Django provides several mechanisms to help developers follow this principle:
Django's URL dispatcher: It allows you to define URL patterns and map them to
corresponding views. By using named URLs and including URL patterns from
other URL configurations, you can avoid hardcoding URLs in multiple places,
promoting code reuse.
Template system: Django's template language supports template inheritance,
allowing you to define base templates that contain common elements shared
across multiple pages. Child templates can then extend the base template and
provide specific content for each page, reducing the need for duplicate HTML
code.
Model inheritance: Django's object-relational mapping (ORM) supports model
inheritance, enabling you to define common fields and behaviors in a base model
and derive specialized models from it. This approach helps avoid duplicating
code and allows for code reuse and extensibility.
Middleware: Django's middleware framework lets you define reusable
components that process requests and responses. Middleware can be used to
handle common tasks such as authentication, session management, and caching,
eliminating the need to repeat the same logic in multiple views.
--------------------------------------------------------------------
Review Questions
1. Explain Django framework with architecture.
2. List and explain the features of Django framework.
3. Define and explain the working process of webservers.
4. Write the procedure to install and configure the Django components.
5. Create the hello world application using Django. Explain with relevant example.
6. Write the procedure to create views.
7. Write short note on Django URL mapping.
8. Explain in details about Django templates with example.
9. Discuss about rendering dynamic content in templates.
10. Outline the DRY principles in Django.
11. Explain in detail about DRY template inheritance in Django.
15
(MR23-1CS0103) Stack Development Frameworks Unit_04
To create Django form we have to create a new file inside the application folder let’s
say file name is forms.py. Now we can write below code inside the forms.py to
create a form.
Syntax:
from django import forms
class FormClassName(forms.Form);
label=forms.FieldType()
label=forms.FiledType(label=’display_label’)
Example: (forms.py)
from django import forms
class StudentRegistration(forms.Form):
name = forms.CharField()
email = forms.EmailField()
1
(MR23-1CS0103) Stack Development Frameworks Unit_04
Now, we need to instantiate the form in views.py file. See, the below code.
views.py
Passing the context of form into “userregistrer” template that looks like this:
userregistrer.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewpoint" content="width=device-
width,initial-scale=1.0">
<title>User Registration</title>
</head>
<body>
<table>
{{form}}
</table>
<input type="submit" value="Submit">
</body>
</html>
2
(MR23-1CS0103) Stack Development Frameworks Unit_04
Run Server and access the form at browser by localhost:8000, and it will produce the
following output.
--------------------------------------------------------------------
Handling user input and validation
The primary functions of Django's form handling include:
1. Display the default form the first time it is requested by the user.
The form may contain blank fields if you're creating a new record, or it may
be pre-populated with initial values (for example, if you are changing a
record, or have useful default initial values).
The form is referred to as unbound at this point, because it isn't associated
with any user-entered data (though it may have initial values).
2. Receive data from a submit request and bind it to the form.
Binding data to the form means that the user-entered data and any errors are
available when we need to redisplay the form.
3. Clean and validate the data.
Cleaning the data performs sanitization of the input fields, such as removing
invalid characters that might be used to send malicious content to the server,
and converts them into consistent Python types.
Validation checks that the values are appropriate for the field (for example,
that they are in the right date range, aren't too short or too long, etc.)
4. If any data is invalid, re-display the form, this time with any user populated values
and error messages for the problem fields.
5. If all data is valid, perform required actions (such as save the data, send an email,
return the result of a search, upload a file, and so on).
6. Once all actions are complete, redirect the user to another page.
3
(MR23-1CS0103) Stack Development Frameworks Unit_04
Example:
forms.py
class StudentRegistration(forms.Form):
name = forms.CharField()
email = forms.EmailField()
views.py
from django.shortcuts import render
from .forms import StudentRegistration
from django.http import HttpResponse
def showformdata(request):
if request.method=='POST':
fm = StudentRegistration(request.POST)
if fm.is_valid():
print('Form Validated')
print('Name:',fm.cleaned_data['name'])
print('email:', fm.cleaned_data['email'])
else:
fm = StudentRegistration()
return render(request,'userregistration.html',{'form':fm})
4
(MR23-1CS0103) Stack Development Frameworks Unit_04
userregistration.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST"> {% csrf_token%}
{{form.as_p}}
<input type="submit" value="Submit">
</form>
</body>
</html>
--------------------------------------------------------------------
Form widgets
A widget is Django’s representation of an HTML input element.
The widget handles the rendering of the HTML, and the extraction of data from a
GET/POST dictionary that corresponds to the widget.
The HTML generated by the built-in widgets uses HTML5 syntax, targeting
<!DOCTYPE html>.
Whenever you specify a field on a form, Django will use a default widget that is
appropriate to the type of data that is to be displayed.
Each form field has an appropriate default widget class, but these can be overridden
as required
Form fields deal with the logic of input validation and are used directly in
templates.
Widgets deal with rendering of HTML form input elements on the web page and
extraction of raw submitted data.
Example
5
(MR23-1CS0103) Stack Development Frameworks Unit_04
Now, we need to instantiate the form in views.py file. See, the below code.
views.py
Passing the context of form into “userregistrer” template that looks like this:
userregistrer.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewpoint" content="width=device-
width,initial-scale=1.0">
<title>User Registration</title>
</head>
<body>
<table>
{{form}}
</table>
<input type="submit" value="Submit">
</body>
</html>
Run Server and access the form at browser by localhost:8000, and it will produce the
following output.
6
(MR23-1CS0103) Stack Development Frameworks Unit_04
--------------------------------------------------------------------
Handling form errors
Built-in Form Field Validations in Django Forms are the default validations that
come predefined to all fields.
Every field comes in with some built-in validations from Django validators. Each
Field class constructor takes some fixed arguments.
The error_messages argument allow us to specify manual error messages for
attributes of the field.
The error_messages argument overrides the default messages that the field will
raise.
Pass in a dictionary with keys matching the error messages that the user want to
override.
Enter the following code into forms.py file of our app. We will be using
CharField and Emailfield in our application.
7
(MR23-1CS0103) Stack Development Frameworks Unit_04
forms.py
class StudentRegistration(forms.Form):
name = forms.CharField(error_messages={
'required': "Enter your Name"})
email = forms.EmailField(error_messages={
'required': "Enter your Email"})
Now to render this form into a view we need a view and a URL mapped to that view.
Let’s create a view first in views.py of our app,
def showformdata(request):
if request.method=='POST':
fm = StudentRegistration(request.POST)
if fm.is_valid():
print('Form Validated')
print('Name:',fm.cleaned_data['name'])
print('email:', fm.cleaned_data['email'])
else:
fm = StudentRegistration()
return
render(request,'userregistration.html',{'form':fm})
Let’s run the server and check what has actually happened, Run
Python manage.py runserver
--------------------------------------------------------------------
8
(MR23-1CS0103) Stack Development Frameworks Unit_04
CRUD operations
CRUD is the acronym for CREATE, READ, UPDATE and DELETE.
These terms describe the four essential operations for creating and managing
persistent data elements, mainly in relational and NoSQL databases.
Applications that use persistent storage—those that retain data even after the
machine is powered down—perform CRUD operations.
CRUD
These are different from operations on data stored in volatile storage, like Random
Access Memory or cache files.
CRUD is extensively used in database applications. This includes Relational
Database Management Systems (RDBMS) like Oracle, MySQL, and PostgreSQL.
It also includes NoSQL databases like MongoDB, Apache Cassandra, and AWS
DynamoDB.
CREATE
The CREATE operation adds a new record to a database.
In RDBMS, a database table row is referred to as a record, while columns are
called attributes or fields.
The CREATE operation adds one or more new records with distinct field
values in a table.
READ
READ returns records (or documents or items) from a database table (or
collection or bucket) based on some search criteria.
The READ operation can return all records and some or all fields.
UPDATE
UPDATE is used to modify existing records in the database.
For example, this can be the change of address in a customer database or price
change in a product database.
Similar to READ, UPDATEs can be applied across all records or only a few,
based on criteria.
An UPDATE operation can modify and persist changes to a single field or to
multiple fields of the record. If multiple fields are to be updated, the database
system ensures they are all updated or not at all.
DELETE
DELETE operations allow the user to remove records from the database.
9
(MR23-1CS0103) Stack Development Frameworks Unit_04
A hard delete removes the record altogether, while a soft delete flags the record
but leaves it in place.
For example, this is important in payroll where employment records need to be
maintained even after an employee has left the company.
How is CRUD performed in a database?
In RDBMS, CRUD operations are performed through Structure Query Language
(SQL) commands.
10
(MR23-1CS0103) Stack Development Frameworks Unit_04
Installation
Authentication support is bundled as a Django contrib module in django.contrib.auth.
By default, the required configuration is already included in the settings.py generated
by django-admin startproject, these consist of two items listed in
your INSTALLED_APPS setting:
1. 'django.contrib.auth' contains the core of the authentication framework, and its
default models.
2. 'django.contrib.contenttypes' is the Django content type system, which allows
permissions to be associated with models you create.
and these items in your MIDDLEWARE setting:
1. SessionMiddleware manages sessions across requests.
2. AuthenticationMiddleware associates users with requests using sessions.
With these settings in place, running the command manage.py migrate creates the
necessary database tables for auth related models and permissions for any models
defined in your installed apps.
User objects
User objects are the core of the authentication system.
They typically represent the people interacting with your site and are used to enable
things like restricting access, registering user profiles, associating content with
creators etc.
Only one class of user exists in Django’s authentication framework, i.e., 'superusers'
or admin 'staff' users are just user objects with special attributes set, not different
classes of user objects.
The primary attributes of the default user are:
username
password
email
first_name
last_name
Creating superusers
Create superusers using the createsuperuser command:
$ python manage.py createsuperuser --username=joe [email protected]
11
(MR23-1CS0103) Stack Development Frameworks Unit_04
You will be prompted for a password. After you enter one, the user will be
created immediately
Authenticating users
Use authenticate() to verify a set of credentials.
It takes credentials as keyword arguments, username and password for the
default case, checks them against each authentication backend, and returns
a User object if the credentials are valid for a backend.
If the credentials aren’t valid for any backend or if a backend
raises PermissionDenied, it returns None.
--------------------------------------------------------------------
Managing user sessions and permissions
Sessions are server-side cookies. Web applications store user inputs on both the
server and client ends.
Sessions refer to the data stored on the server end, while cookies refer to the data
stored on the client end.
The Django framework used these sessions to guarantee the security of the
application.
The following picture illustrates how the Django sessions work:
When a web browser makes the first HTTP request to the web server, the session
middleware starts a new session. The session middleware generates a large and
random number which is called a session identifier and sends it back to the web
browser as a cookie.
For the subsequent requests, the session middleware matches the value sessionid in
the cookie sent by the web browser with the session identifier stored on the web
server and associates the session data with the HTTP request object.
12
(MR23-1CS0103) Stack Development Frameworks Unit_04
To use sessions, you need to ensure that the MIDDLEWARE settings of your project
(settings.py) contain the session middleware like this:
MIDDLEWARE = [
# other middleware
'django.contrib.sessions.middleware.SessionMiddleware',
# ...
]
The session middleware is added to the MIDDLEWARE by default when you create
a new project using the startproject command.
The session middleware enables sessions via the session property of the request
object (HttpRequest): request.session
The request.session is a dictionary that allows you to store and retrieve session data.
The request.session accepts any object that can be serialized to JSON by default.
Unlike other objects, the request.session persists from one HTTP request to the next
request.
To set a variable in the session, you can use the request.session like this:
request.session['visit'] = 1
This statement sets the visit variable to 1.
To retrieve a session key, you use the get() method of the request.session object:
request.session.get('visit')
To delete a key in the session, you use the del statement:
del request.session['visit']
Setting Django sessions
By default, Django stores session data in a database using the Session model of
the django.contrib.sessions application. However, you can choose other session
engines using the SESSION_ENGINE.
Django provides the following options for storing session data:
Options Description
Database sessions Store session data in the django_session of the database. This
is the default engine.
File-based sessions Store session data in the filesystem.
Cached sessions Store session data in a cache backend. To set the cache
backend, you use the CACHES setting.
Cached database sessions Store session data in a write-through cache and database. If
the data is not in the cache, Django will read the session data
from the database.
Cookie-based sessions Store session data in the cookies that are sent to the web
browser.
13
(MR23-1CS0103) Stack Development Frameworks Unit_04
--------------------------------------------------------------------
14
(MR23-1CS0103) Stack Development Frameworks Unit_04
15
(MR23-1CS0103) Stack Development Frameworks Unit_04
The super user has full access to all models in the admin and can add, change and
delete any model record.
For adding new user click the green plus sign on the right of the Users entry on the
admin home page. Enter a username and password and click save to add the new
user.
Changing Passwords
python manage.py changepassword username
16
(MR23-1CS0103) Stack Development Frameworks Unit_04
17
(MR23-1CS0103) Stack Development Frameworks Unit_05
1
(MR23-1CS0103) Stack Development Frameworks Unit_05
Select Directory and then give a name to our project and then Click on Create.
2
(MR23-1CS0103) Stack Development Frameworks Unit_05
Open the terminal in pycharm and type the following command to install Django
pip install django
This command fetches the django package from the Python Package Index (PyPI)
using pip. After the installation has completed, you can pin your dependencies to
make sure that you’re keeping track of which Django version you installed:
Type the following Command in pycharm Terminal to check the Django version.
python -m django –version
Type the following Command in pycharm Terminal to install Django REST
Framework.
pip install djangorestframework
3
(MR23-1CS0103) Stack Development Frameworks Unit_05
To run the application in django rest framework after creating the project Add
'rest_framework' to your INSTALLED_APPS setting.
INSTALLED_APPS = [
...
'rest_framework',
]
--------------------------------------------------------------------
Step 4: Type the following Command in pycharm Terminal to install Django REST
Framework.
pip install djangorestframework
4
(MR23-1CS0103) Stack Development Frameworks Unit_05
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
@api_view(['GET'])
def getData(request):
person = {'name':'Denny','age':'25'}
return Response(person)
urlpatterns = [
5
(MR23-1CS0103) Stack Development Frameworks Unit_05
path('', views.getData),
path('add/', views.addItem),
]
--------------------------------------------------------------------
RESTful API
A RESTful API is an architectural style for an application program interface (API)
that uses HTTP requests to access and use data.
That data can be used to GET, PUT, POST and DELETE data types, which refers to
the reading, updating, creating and deleting of operations concerning resources.
An API for a website is code that allows two software programs to communicate
with each other. The API spells out the proper way for a developer to write a
program requesting services from an operating system or other application.
A RESTful API -- also referred to as a RESTful web service or REST API -- is based
on representational state transfer (REST), which is an architectural style and
approach to communications often used in web services development.
REST technology is generally preferred over other similar technologies.
This tends to be the case because REST uses less bandwidth, making it more suitable
for efficient internet usage.
RESTful APIs can also be built with programming languages such as JavaScript or
Python.
6
(MR23-1CS0103) Stack Development Frameworks Unit_05
HTTP Methods - REST uses standard HTTP methods to define interaction with
resources. GET retrieves representations, POST creates resources, PUT updates
them, DELETE deletes them.
Request Messages - Clients send requests to REST API endpoints with HTTP
headers containing metadata like authorization tokens, content-type, accept headers
etc. Parameters help filter result sets or bind data.
Response Messages - Servers return HTTP response codes indicating outcomes
along with response headers describing the content. The message body contains
representations of resources or data payloads.
Self-documentation - REST APIs use HTTP conventions for response codes, verbs,
and media types so APIs self-document how they are supposed to be used by
clients.
--------------------------------------------------------------------
API Endpoint
An endpoint is a component of an API, while an API is a set of rules that allow
two applications to share resources. Endpoints are the locations of the resources, and
the API uses endpoint URLs to retrieve the requested resources.
7
(MR23-1CS0103) Stack Development Frameworks Unit_05
In this diagram above, all the requests having the same base URL go to the same
server.
For example, https://myserver1.com requests go to “Web Server 1,” and
https://myserver2.com requests go to “Web Server 2“.
The webserver takes different actions based on the API endpoint. We use the /users
endpoint to manage the collection of users as a whole and /users/{id} endpoint to
manage individual users.
Endpoints are an important concept in API design and are used to define the various
resources and actions that can be performed through an API.
8
(MR23-1CS0103) Stack Development Frameworks Unit_05
HTTP DELETE: Delete one or more users from the collection using the HTTP
DELETE technique
Here, the same endpoint (/users) supports multiple protocols (GET, POST, PUT,
DELETE) by allowing different HTTP methods. As a result, the API may offer a
variety of functions for controlling the group of users from a single endpoint.
9
(MR23-1CS0103) Stack Development Frameworks Unit_05
CRUD
if Item.objects.filter(**request.data).exists():
raise serializers.ValidationError('This data already
exists')
if item.is_valid():
item.save()
return Response(item.data)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
READ:
Returns records (or documents or items) from a database table (or collection or
bucket) based on some search criteria.
This view_items function will either show all the data or filtered data queried by
the user according to the category, subcategory, or name.
@api_view(['GET'])
def view_items(request):
if request.query_params:
items =
Item.objects.filter(**request.query_params.dict())
else:
items = Item.objects.all()
if items:
serializer = ItemSerializer(items, many=True)
return Response(serializer.data)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
10
(MR23-1CS0103) Stack Development Frameworks Unit_05
UPDATE:
Used to modify existing records in the database.
Update view uses the POST method to update a particular item from the
database
@api_view(['POST'])
def update_items(request, pk):
item = Item.objects.get(pk=pk)
data = ItemSerializer(instance=item, data=request.data)
if data.is_valid():
data.save()
return Response(data.data)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
DELETE:
Allow the user to remove records from the database.
Delete view function we will use the DELETE method to remove the items.
@api_view(['DELETE'])
def delete_items(request, pk):
item = get_object_or_404(Item, pk=pk)
item.delete()
return Response(status=status.HTTP_202_ACCEPTED)
--------------------------------------------------------------------
11
(MR23-1CS0103) Stack Development Frameworks Unit_05
Types of authentication
BasicAuthentication
This authentication scheme uses HTTP Basic Authentication, signed against a user's
username and password. Basic authentication is generally only appropriate for testing.
If successfully authenticated, BasicAuthentication provides the following credentials.
request.user will be a Django User instance.
request.auth will be None .
Unauthenticated responses that are denied permission will result in an HTTP 401
Unauthorized response with an appropriate WWW-Authenticate header. For example:
WWW-Authenticate: Basic realm="api"
TokenAuthentication
This authentication scheme uses a simple token-based HTTP Authentication scheme.
Token authentication is appropriate for client-server setups, such as native desktop
and mobile clients.
To use the TokenAuthentication scheme you'll need to configure the authentication
SessionAuthentication
This authentication scheme uses Django's default session backend for
authentication. Session authentication is appropriate for AJAX clients that are
running in the same session context as your website.
If successfully authenticated, SessionAuthentication provides the following
credentials.
12
(MR23-1CS0103) Stack Development Frameworks Unit_05
RemoteUserAuthentication
This authentication scheme allows you to delegate authentication to your web
server, which sets the REMOTE_USER environment variable.
To use it, you must have django.contrib.auth.backends.RemoteUserBackend (or a
subclass) in your AUTHENTICATION_BACKENDS setting. By
default, RemoteUserBackend creates User objects for usernames that don't already
exist.
--------------------------------------------------------------------
API View to handle Requests and Responses
Request
REST framework's Request class extends the standard HttpRequest, adding support
for REST framework's flexible request parsing and request authentication.
Request parsing
REST framework's Request objects provide flexible request parsing that allows
you to treat requests with JSON data or other media types in the same way that
you would normally deal with form data.
.data
request.data returns the parsed content of the request body. This is similar to
the standard request.POST and request.FILES attributes except that:
It includes all parsed content, including file and non-file inputs.
It supports parsing the content of HTTP methods other than POST , meaning
that you can access the content of PUT and PATCH requests.
It supports REST framework's flexible request parsing, rather than just
supporting form data. For example you can handle incoming JSON
data similarly to how you handle incoming form data.
.query_params
request.query_params is a more correctly named synonym for request.GET .
For clarity inside your code, we recommend
using request.query_params instead of the Django's standard request.GET .
Doing so will help keep your codebase more correct and obvious - any HTTP
method type may include query parameters, not just GET requests.
13
(MR23-1CS0103) Stack Development Frameworks Unit_05
.parsers
The APIView class or @api_view decorator will ensure that this property is
automatically set to a list of Parser instances, based on the parser_classes set
on the view or based on the DEFAULT_PARSER_CLASSES setting.
Response
REST framework supports HTTP content negotiation by providing
a Response class which allows you to return content that can be rendered into
multiple content types, depending on the client request.
The Response class subclasses
Django's SimpleTemplateResponse . Response objects are initialised with data,
which should consist of native Python primitives. REST framework then uses
standard HTTP content negotiation to determine how it should render the final
response content.
14
(MR23-1CS0103) Stack Development Frameworks Unit_05
Review Questions
1. Illustrate the REST architecture in detail.
2. Summarize the procedure to setting up Django REST Framework.
3. How to Build Web API using Django REST?
4. What is an API Endpoint? How to create An API Endpoint with Django REST
Framework?
5. Define and explain RESTful API.
6. Explain in detail CRUD operation with Django REST Framework.
7. List and describe different User Authentication in Django REST Framework (DRF).
8. Show how to use API View to handle Requests and Responses.
15