0% found this document useful (0 votes)
17 views109 pages

SDF - Supporting - Reference Material

Full Stack Development encompasses both front-end and back-end web application development, requiring developers to be proficient in various technologies and tools. The need for full stack developers arises from the advantages they provide, such as cost-effectiveness, enhanced scalability, and improved client satisfaction. The document also outlines essential front-end and back-end tools, including languages like HTML, CSS, JavaScript, and PHP, as well as frameworks like AngularJS, React.js, and Bootstrap.

Uploaded by

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

SDF - Supporting - Reference Material

Full Stack Development encompasses both front-end and back-end web application development, requiring developers to be proficient in various technologies and tools. The need for full stack developers arises from the advantages they provide, such as cost-effectiveness, enhanced scalability, and improved client satisfaction. The document also outlines essential front-end and back-end tools, including languages like HTML, CSS, JavaScript, and PHP, as well as frameworks like AngularJS, React.js, and Bootstrap.

Uploaded by

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

(MR23-1CS0103) Stack Development Frameworks Unit_01

Unit_01 - Introduction to Full Stack Development Frameworks

Full Stack Development


 Full Stack Development refers to the software development process of both front end
(client side) and back end (server side) portions of web application.
 “Full-stack development” refers to a collection of abilities and skills that are an
indispensable precondition to developing web-based applications and websites on
both the front end and back end.
 Full stack development is the process of designing, creating, testing, and deploying a
complete web application from start to finish.
 It involves working with various technologies and tools, including front-end web
development, back-end web development, and database development. And full stack
development is a term used to describe a software engineer or developer who works
with both the front and back end of a website or application.
 A full-stack developer is comfortable working with front-end and back-end
technologies that power a website or application.
 A full stack developer is one who can single-handedly implement both the front-end
and back-end workflows, like placing the order or changing the user profile.

Fig: Demonstration of full stack development in an end-to-end workflow

 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

Need of Full Stack Development


In a modern world with a lot a technologies, instead of depending on a number of
software professionals separately for front–end and back-end tasks to handle, a need of
full stack development is required who can handle all the technologies required for
developing a software project. This includes a number of advantages like:

 Saves Money and Time


Full-stack development is cost-effective when the same developer or team works
on both the front and back end.
 Hiring a full-stack developer lowers the cost of developing an application because
the developer is conversant and proficient with both the frontend and the backend
technologies. Therefore, businesses need not invest twice as much in designing an
application.
 It also facilitates adding fewer individuals to the project team, reducing
operational and contractual expenses.
 Full-stack developers have the ability to save business money and resources as
they can work on both the front end and the back end of a project on their own.
Most full-stack engineers (55.2% back-end and 37.1%) claim to be in the latter
category, according to research conducted by Stack Overflow in 2020.
 Rounded Solution and Adaptable
 However, we also agree that a person with knowledge of all levels can create a
comprehensive solution with fewer bugs and greater efficiency.
 In general, frontend and backend development are proficient in their respective
technologies. Still, the primary advantage of full-stack development is that the
developers are proficient in both frontend and backend technologies and can
construct complicated apps efficiently from scratch.
 As well as, the full-stack developer is capable of doing all the duties of a backend
developer and a frontend developer alone. This makes troubleshooting the code
and testing the product significantly simpler.
 Unique Codes
 No longer must the team’s project manager coordinate with the frontend and
backend developers to make the program function.
 Full-stack developers can now develop applications and write flawlessly unique
scripts relatively easily.
 This eliminates the requirement to mix and connect code from two distinct
application development ends.

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

 Comprehensive Work design


 While collaborating, members of a team of Full Stack developers can split the
design and development task according to the flow’s requirements.
 In addition to this, a single Full Stack developer has the ability to switch between
tasks in accordance with the requirements of the project at hand.

Fig: The need of full stack development


---------------------------------------------------------------------------------------------------------------------
Introduction to Front end Environment Tools
 Front end is the visible part of website or web application which is responsible for
user experience. The user directly interacts with the front end portion of the web
application or website.
 The front end is a combination of two different elements: the graphic design (the look)
and the user interface (the feel). Each of these is created independently, with most of
the technical work going into the user interface using web languages like HTML, CSS,
and JavaScript.

 Front End Languages


The front-end portion is built by using some languages which are discussed below.

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

 It is lightweight and most commonly used as a part of web pages, whose


implementations allow client-side script to interact with the user and make dynamic
pages. It is an interpreted programming language with object-oriented capabilities.

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.

 Front-End Frameworks and Libraries


1. AngularJS
 AngularJs is a JavaScript open-source front-end framework that is mainly used to
develop single-page web applications (SPAs). It is a continuously growing and
expanding framework which provides better ways for developing web applications.
It changes the static HTML to dynamic HTML. It is an open-source project which
can be free. It extends HTML attributes with Directives, and data is bound with
HTML.
Advantages of AngularJS over other JavaScript frameworks:
 Dependency Injection: Dependency Injection specifies a design pattern in which
components are given their dependencies instead of hard coding them within the
component.
 Two way data binding: AngularJS creates a two way data-binding between the
select element and the orderProp model. orderProp is then used as the input for the
orderBy filter.

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

and JavaScript. Elaborating on the terms, jQuery simplifies HTML document


traversing and manipulation, browser event handling, DOM animations, Ajax
interactions, and cross-browser JavaScript development.
Advantages of jQuery
 Wide range of plug-ins that allows developers to create plug-ins on top of the
JavaScript library.
 Large development community.
 It is a lot easier to use compared to standard javascript and other javascript libraries.
 It lets users develop Ajax templates with ease. Ajax enables a sleeker interface where
actions can be performed on pages without requiring the entire page to be reloaded.
 Being Light weight and a powerful chaining capabilities makes it stronger.

 Some other libraries and frameworks are Semantic-UI, Foundation, Materialize,


Backbone.js, Ember.js, etc.
---------------------------------------------------------------------------------------------------------------------
Introduction to Backend Environment Tools
The back end refers to the server-side development of web application or website
with a primary focus on how the website works. It is responsible for managing the
database through queries and APIs by client-side commands. This type of website mainly
consists of three parts front end, back end, and database.

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

Why use PHP


PHP is a server-side scripting language, which is used to design the dynamic web
applications with MySQL database.
 It handles dynamic content, database as well as session tracking for the website.
 You can create sessions in PHP.
 It can access cookies variable and also set cookies.
 It helps to encrypt the data and apply validation.
 PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and
many more.
 Using PHP language, you can control the user to access some pages of your website.
 As PHP is easy to install and set up, this is the main reason why PHP is the best
language to learn.

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

 Object-Oriented Programming Language: Organizing the program in the terms of


a collection of objects is a way of object-oriented programming, each of which
represents an instance of the class.
 Simple: Java is one of the simple languages as it does not have complex features
like pointers, operator overloading, multiple inheritances, and Explicit memory
allocation.
 Secure: Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
 No explicit pointer
 Java Programs run inside a virtual machine sandbox
 Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It
adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
 Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
 Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.
 Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS,
Cryptography, etc.
 Multithreading: Java supports multithreading. It is a Java feature that allows
concurrent execution of two or more parts of a program for maximum utilization of
the CPU.
 Portable: Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
 Dynamic: Java is a dynamic language. It supports the dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.
 Java supports dynamic compilation and automatic memory management
(garbage collection).

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.

Some more back-end programming/scripting languages are spring, Laravel,


C#, Ruby, GO, etc.
---------------------------------------------------------------------------------------------------------------------
Client/Server architecture
 A client - server architecture is a model in which computers such as servers provide
the network services to the other computers such as clients to perform a user based
tasks. This model is known as client-server networking model.

12
(MR23-1CS0103) Stack Development Frameworks Unit_01

 The application programs using the client-server architecture should follow the given
below strategies:

Fig: Client – Server Model


 An application program is known as a client program, running on the local machine
that requests for a service from an application program known as a server program,
running on the remote machine.
 A client program runs only when it requests for a service from the server while the
server program runs all time as it does not know when its service is required.
 A server provides a service for many clients not just for a single client. Therefore, we
can say that client-server follows the many-to-one relationship. Many clients can use
the service of one server.
 Services are required frequently, and many users have a specific client-server
application program. For example, the client-server application program allows the
user to access the files, send e-mail, and so on. If the services are more customized,
then we should have one generic application program that allows the user to access
the services available on the remote computer.

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.

 Client-Server architecture example


1. Mail servers
Email servers are used for sending and receiving emails. There are different software
that allows email handling.

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.

 Components of Client-Server architecture:


Essentially, three components are required to make client-server architecture work. The
three components are workstations, servers, and networking devices. Let us, now,
discuss them in detail:

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

 How does client-server architecture work?


A client-server architecture has a client node and a server node. While the server
functions as the producer, clients are considered consumers. A consumer sends a request

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.

Here is an explanation of the functioning of the client-server model:

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

 Types of client server architecture


There are three types of client server architecture available in database management
system. These are listed below.
(a) Single tier client server computing model
(b) Two tier client server computing model
(c) Three tier client server computing model

 Single tier client server architecture.


Single tier architecture is the first type of client server
computing model. In single tire client server computing
model, the client server database system used on a
personal computer. In single tire system, the database is
centralized, which means the DBMS software and the data
in one location and the dumb terminals were used to access
the database management system.

 Two-tier client server computing model


Two-tier client server architecture is the second type of
client server computing model. It uses two computers and
one client/server system. At the early stages, client server
computing it was called two-tier computing model in
which client is considered as data capture and validation
tier and server was considered as data storage tire.

Problems in two tier architecture:


In 1990s, when applications were more complex and used with hundreds or thousands
of end users, the two tier server model could not meet the need of the enterprise.

15
(MR23-1CS0103) Stack Development Frameworks Unit_01

(a) An efficient client requiring considerable resources on client’s computer to run


effectively. This includes disk space, RAM, CPU.
(b) Client machines require administration which results overhead at the server end.

 Three tier architecture.


Three tier architecture is the improvement over two tier
architecture. Three tier architecture has three layers. The
first layer is the user interface which runs on client system.
The second layer is called the application server. It is used
for business logic and data processing. The third layer is
known as database server. It is a database management
system which stores the data as needed by the middle layer.

 Advantages of Client-server architecture:


 Centralized: Centralized back-up is possible in client-server networks, i.e., all the data
is stored in a server.
 Security: These networks are more secure as all the shared resources are centrally
administered.
 Performance: The use of the dedicated server increases the speed of sharing resources.
This increases the performance of the overall system.
 Scalability: We can increase the number of clients and servers separately, i.e., the new
element can be added, or we can add a new node in a network at any time.

 Disadvantages of Client-Server architecture:


 Traffic Congestion is a big problem in Client/Server networks. When a large number
of clients send requests to the same server may cause the problem of Traffic
congestion.
 It does not have a robustness of a network, i.e., when the server is down, then the
client requests cannot be met.
 A client/server network is very decisive. Sometimes, regular computer hardware
does not serve a certain number of clients. In such situations, specific hardware is
required at the server side to complete the work.
 Sometimes the resources exist in the server but may not exist in the client. For
example, if the application is web, then we cannot take the print out directly on
printers without taking out the print view window on the web.

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

 MongoDB — document database


 Express(.js) — Node.js web framework
 Angular(.js) — a client-side JavaScript framework
 Node(.js) — the premier JavaScript web server

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.

 Mean Stack Architecture:


Here, each module communicates with the others in order to have a flow of the data from
Server/Backend to Client/Frontend.

Fig: Mean Stack Architecture


 Initially, the client makes a request which is processed by the AngularJS

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

 It allows developers to spin up robust APIs (Application Programming Interface) and


web servers much easier and simpler.
 Express makes robust web servers easier to organize your application's functionality
with routing and middleware.
 It also adds helpful functionalities to Node.js HTTP (HyperText Transfer Protocol)
objects.
 It is an important component of the MERN and MEAN Stack and is used to build fast,
maintainable, and robust productions web applications.

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.

Each of these four technologies plays an important role in providing an end-to-end


framework for the developers. Even these four technologies play an important role in the
development process of web applications.

21
(MR23-1CS0103) Stack Development Frameworks Unit_01

 Architectural Structure of MERN Stack:


MERN has a 3-tier Architecture system mainly consisting of 3 layers -
These layers are as follows:
 Web as front-end tier
 Server as the middle tier
 Database as backend tier

Fig: MERN Stack Architecture


Web or front-end tier - The top tier of the MERN stack is mainly handled by React.js. It
is one of the most prominent used open-source front-end JavaScript libraries used for
building Web applications. It is famous for creating dynamic client-side applications.
React will help you construct complex interfaces by using single components. It also
connects those complex interfaces to data available on the backend server. React is used
to create mobile applications (React Native) and web applications. React allows the
reusability of code and can easily support it, which has many benefits and is much time
saver. It permits users to create large web applications that can easily change the data of
the page even without reloading the page.

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.

 Advantages of MERN Stack


 For a smooth development of any web application or mobile app, it supports MVC
(Model View Controller) architecture; the main purpose of this architecture is to
separate the presentation details with the business logic.
 It covers all the web development stages starting from front-end development to
backend development with JavaScript.
 It is an open-source framework mainly used to develop web-based or mobile
applications and is supported by the community.
 It is very fast and efficient compared to MEAN Stack and mostly suitable for small
applications, whereas MEAN Stack is suitable for developing large applications.
---------------------------------------------------------------------------------------------------------------------
MEVN stack
MEVN stack is one of the most popularly used collections of technologies that enable
faster application development. MEVN stands for MongoDB, Express, Vue, and Node,
after the four key technologies that make up the stack.

 M – MongoDB: document database


 E – ExpressJS: Node.js web framework
 V – VueJS: A client-side JavaScript framework
 N – NodeJS: Premier JavaScript web server
One of the main reasons the MEVN stack is popular is because the application is built
with only one language i.e JavaScript.
It solves the problem of implementing different languages at the frontend and backend.

Fig: MEVN Stack

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

 Advantages of MEVN Stack:


 The biggest advantage of MEVN is that javascript is used on all levels of development
from client-side to server-side which simplifies the process and makes development
faster and efficient.
 It is platform-independent.
 MVC architecture in the back-end organizes the server-side and hence back-end
development becomes faster and more efficient.
 In MEVN stack the Vue.JS is faster and easy to learn.
---------------------------------------------------------------------------------------------------------------------
LAMP Stack
 LAMP is an open-source Web development platform that uses Linux as the operating
system, Apache as the Web server, MySQL as the relational database management
system and PHP/Perl/Python as the object-oriented scripting language.
 LAMP is also called a LAMP stack because it has four layers in its platform. Stacks on
various operating systems may be installed.
 LAMP is an example of a web service stack, named as an acronym. The LAMP
components are largely interchangeable and not limited to the original selection.
LAMP is suitable for building dynamic web sites and web applications.
 The LAMP model, although traditionally composed of open source free software, has
been adapted to another part since its development.
 Developers that use these tools with a Windows operating system instead of Linux
are said to be using WAMP, with a Macintosh system MAMP, and with a Solaris
system SAMP.
 Linux, Apache, MySQL and PHP, all of them add something unique to the
development of high-performance web applications. Originally popularized from the
phrase Linux, Apache, MySQL, and PHP, the acronym LAMP now refers to a generic
software stack model.

 LAMP Stack Components


Linux based web servers consist of four software components. These components are
arranged in layers supporting one another and make up the software stack. Websites and
Web Applications run on top of this underlying stack. The common software components
are as follows:
1. Linux:
 Linux started in 1991. It sets the foundation for the stack model. All other layers are
run on top of this layer.
 It is an open-source and free operating system. It is endured partly because it's
flexible, and other operating systems are harder to configure.

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.

Fig: LAMP Architecture

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.

Fig: MVC architecture


Component of the MVC architecture are.
Model:
The model contains the business logic of the application, and rules to modify the data. In
Ruby on Rails, they handle the interaction with related elements in the database. They
indicate the data in the database and perform accurate verifications.
View:
It maintains the view display logic. It displays the data retrieved from the model in a
visually appealing way, using HTML, CSS, and JavaScript.
Controller:
The controller is the glue that connects the model and the view. It retrieves data from the
model, processes it, and passes it on to the view to be displayed. It also handles user

28
(MR23-1CS0103) Stack Development Frameworks Unit_01

interactions, such as submitting forms and communicates with the model to update the
data.

Feature of Ruby on Rails


With both the front and backend, Ruby on Rails is a complete version of creating web
applications. Other frameworks are either exclusively for the back end or the front end.
Among Ruby on Rails’ key attributes are the following:
 Model-view-controller Architecture: Ruby on Rails used MVC architecture, and it
contains three components, i.e., model, view, and controller. Here, the model is used
to maintain the relationship between object and database, the view is templates that
are used to build the data users for web applications, and the controller is used to
merge model and view together. MVC is generally used for developing user interfaces
that divide the data into three interconnected components so that it can separate the
internal representation of the information from the way it presents to and get from
the user.
 Active Records: The active record framework is introduced in Ruby on Rails. It is a
powerful library that allows the developer to design the database interactive queries.
 Built-in Testing: Ruby on Rails provides its own set of tests that will run on your
code. It will save time and effort.
 Programming Language: This syntax of Ruby on Rails is simple because the syntax
of the Ruby programming language is close to English, so it is always easier to
structure your thinking and writing it into code.
 MetaProgramming: Ruby on rails uses the metaprogramming technique to write
programs.
 Convention over configuration: In Ruby on Rails, a programmer can only specify the
unconventional aspects of the application.
 Scaffolding: Ruby on rails provides a scaffolding feature in which the developer is
allowed to define how the application database works. After defining the work of the
application database the framework automatically generates the required code
according to the given definition. This technique creates interfaces automatically.

Advantages of Ruby on Rails


 Tooling: Rails provides tooling that helps us to deliver more features in less time.
 Libraries: There’s a 3rd party module (gem) for just about anything we can think of.
 Code Quality: Ruby code quality significantly higher than PHP or NodeJS
equivalents.
 Test Automation: The Ruby community is big into and test automation and testing.
 Large Community: Ruby is large in the community.
 Productivity: Ruby is incredibly fast from another language. Its productivity is high.
---------------------------------------------------------------------------------------------------------------------

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.

Fig: MVT based control flow


 Here, a user requests for a resource to the Django, Django works as a controller and
check to the available resource in URL.

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

Unit_02 - Database Architecture


Introduction to Databases
What is Data?
 Data is a collection of a distinct small unit of information. It can be used in a variety
of forms like text, numbers, media, bytes, etc. it can be stored in pieces of paper or
electronic memory, etc.
 In computing, Data is information that can be translated into a form for efficient
movement and processing. Data is interchangeable.

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

File System vs DBMS


 A file system is a technique of arranging the files in a storage medium like a hard disk,
pen drive, DVD, etc. It helps user to organize the data and allows easy retrieval of files
when they are required. It mostly consists of different types of files like mp3, mp4, txt,
doc, etc. that are grouped into directories.
 A file system enables you to handle the way of reading and writing data to the storage
medium. It is directly installed into the computer with the Operating systems such as
Windows and Linux.
 Database Management System (DBMS) is a software for storing and retrieving user's
data while considering appropriate security measures. It consists of a group of
programs that manipulate the database. The DBMS accepts the request for data from
an application and instructs the DBMS engine to provide the specific data. In large
systems, a DBMS helps users and other third-party software to store and retrieve data.

File System DBMS


A file system is a software that manages DBMS or Database Management System is
and organizes the files in a storage a software application. It is used for
medium. It controls how data is stored accessing, creating, and managing
and retrieved. databases.
The file system provides the details of DBMS gives an abstract view of data that
data representation and storage of data. hides the details
Storing and retrieving of data can't be DBMS is efficient to use as there are a wide
done efficiently in a file system. variety of methods to store and retrieve
data.
It does not offer data recovery processes. There is a backup recovery for data in
DBMS.
The file system doesn't have a crash DBMS provides a crash recovery
recovery mechanism. mechanism
Protecting a file system is very difficult. DBMS offers good protection mechanism.
In a file management system, the The redundancy of data is low in the DBMS
redundancy of data is greater. system.
Data inconsistency is higher in the file Data inconsistency is low in a database
system. management system.
The file system offers lesser security. Database Management System offers high
security.
File System allows you to stores the data Database Management System stores data
as isolated data files and entities. as well as defined constraints and
interrelation.
Not provide support for complicated Easy to implement complicated
transactions. transactions.
The centralization process is hard in File Centralization is easy to achieve in the
Management System. DBMS system.

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

Physical Schema (or) internal level


 A Physical schema defines, how the data or information is stored physically in the
storage systems in the form of files & indices.
 The Database administrator chooses where and how to store the data in the different
blocks of storage.

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.

Logical Schema (or) Conceptual Level


 The conceptual schema describes the design of a database at the conceptual level.
 The conceptual schema describes the structure of the whole database.
 The conceptual level describes what data are to be stored in the database and also
describes what relationship exists among those data.
 In the conceptual level, internal details such as an implementation of the data
structure are hidden.
 Programmers and database administrators work at this level.

View Schema (or) External Level


 At the external level, a database contains several schemas that sometimes called as
subschema. The subschema is used to describe the different view of the database.
 Each view schema describes the database part that a particular user group is
interested and hides the remaining database from that user group.
 The view schema describes the end user interaction with database systems.
---------------------------------------------------------------------------------------------------------------------
Data Independence
 Data Independence is defined as a property of DBMS that helps you to change the
Database schema at one level of a database system without requiring to change the
schema at the next higher level. Data independence helps you to keep data separated
from all programs that make use of it.
 User can use this stored data for computing and presentation. In many systems, data
independence is an essential function for components of the system.

Types of Data Independence


In DBMS there are two types of data independence,
 Physical data independence
 Logical data independence

5
(MR23-1CS0103) Stack Development Frameworks Unit_02

Physical Data Independence


 Physical data independence helps you to separate conceptual levels from the
internal/physical levels. It allows you to provide a logical description of the database without
the need to specify physical structures. Compared to Logical Independence, it is easy to
achieve physical data independence.
 With Physical independence, you can easily change the physical storage structures or
devices with an effect on the conceptual schema. Any change done would be absorbed
by the mapping between the conceptual and internal levels. Physical data
independence is achieved by the presence of the internal level of the database and
then the transformation from the conceptual level of the database to the internal level.

Examples of changes under Physical Data Independence


Due to Physical independence, any of the below change will not affect the conceptual
layer.
 Using a new storage device like Hard Drive or Magnetic Tapes
 Modifying the file organization technique in the Database
 Switching to different data structures.
 Changing the access method & Modifying indexes.
 Changes to compression techniques or hashing algorithms.
 Change of Location of Database from say C drive to D Drive

Logical Data Independence


 Logical Data Independence is the ability to change the conceptual scheme without
changing External views

 Any change made will be absorbed by the mapping between external and conceptual
levels.

6
(MR23-1CS0103) Stack Development Frameworks Unit_02

 When compared to Physical Data independence, it is challenging to achieve logical


data independence.

Examples of changes under Logical Data Independence


Due to Logical independence, any of the below change will not affect the external layer.
 Add/Modify/Delete a new attribute, entity or relationship is possible without a
rewrite of existing application programs
 Merging two records into one
 Breaking an existing record into two or more records
---------------------------------------------------------------------------------------------------------------------
Database Architecture
 The architecture of a database system is greatly influenced by the underlying
computer system on which the database system runs. Database systems can be
centralized, or client-server, where one server machine executes work on behalf of
multiple client machines.
 The DBMS accepts SQL commands generated from a variety of user interfaces,
produces query evaluation plans, executes these plans against the database, and
returns the answers. (This is a simplification: SQL commands can be embedded in
host-language application programs, e.g., Java or COBOL programs. We ignore these
issues to concentrate on the core DBMS functionality.)
 When a user issues a query, the parsed query is presented to a query optimizer, which
uses information about how the data is stored to produce an efficient execution plan
for evaluating the query.
 An execution plan is a blueprint for evaluating a query, usually represented as a tree
of relational operators (with annotations that contain additional detailed information
about which access methods to use, etc.). Relational operators serve as the building
blocks for evaluating queries posed against the data.
 The code that implements relational operators sits on top of the file and access
methods layer. This layer supports the concept of a file, which, in a DBMS, is a
collection of pages or a collection of records.
 Heap files, or files of unordered pages, as well as indexes are supported. In addition
to keeping track of the pages in a file, this layer organizes the information within a
page.
 The files and access methods layer code sits on top of the buffer manager, which
brings pages in from disk to main memory as needed in response to read requests.
 The lowest layer of the DBMS software deals with management of space on disk,
where the data is stored. Higher layers allocate, deallocate, read, and write pages
through (routines provided by) this layer, called the disk space manager.

7
(MR23-1CS0103) Stack Development Frameworks Unit_02

Fig: System Architecture

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

Type of Database models


1. Hierarchical Model
2. Network Model
3. Entity-relationship Model
4. Relational Model
5. Object-oriented Model
6. NoSQL Model
7. Graph Model

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

Advantages/Disadvantages of the Hierarchical Model


 Because it has one-to-many relationships between different types of data so it is
easier and fast to fetch the data.

9
(MR23-1CS0103) Stack Development Frameworks Unit_02

 Hierarchical model is less flexible.


 It doesn't support many-to-many relationships.

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

Advantages of the ER Model


 It is easy to understand and design.
 Using the ER model we can represent data structures easily.
 As the ER model cannot be directly implemented into a database model, it is just
a step toward designing the relational database model.

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.

Advantages of the Relational Model


 It's simple and easy to implement.
 Poplar database software is available for this database model.
 It supports SQL using which you can easily query the data.

5. Object-oriented Model
 In this model, data is stored in the form of objects.

11
(MR23-1CS0103) Stack Development Frameworks Unit_02

 The behavior of the object-oriented database model is just like object-oriented


programming.
 A very popular example of an Object Database management system
or ODBMS is MongoDB which is also a NoSQL database.
 This database model is not mature enough as compared to the relational database
model.

Advantages of the Object-oriented Model


 It can easily support complex data structures, with relationships.
 It also supports features like Inheritance, Encapsulation, etc.

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.

Advantages of the NoSQL Model


 NoSQL database model is scalable.
 This database model functions with high performance.
 The NoSQL database model can handle large volumes of data.

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.

Advantages of the Graph Model


 It handles complex relationships very well.
 In the modern world where there is so much data and the data has to be related in
different ways, the graph database model is very useful.
---------------------------------------------------------------------------------------------------------------------
RDBMS
 RDBMS stands for Relational Database Management System.
 The relational model in DBMS is an abstract model used to organize and manage the
data stored in a database. It stores data in two-dimensional inter-related tables, also
known as relations in which each row represents an entity and each column
represents the properties of the entity.
 All modern database management systems like SQL, MS SQL Server, IBM DB2,
ORACLE, My-SQL, and Microsoft Access are based on RDBMS.
 It is called Relational Database Management System (RDBMS) because it is based on
the relational model introduced by E.F. Codd.

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

Types of Keys in Database Management System


There are mainly seven different types of Keys in DBMS and each key has it’s different
functionality:
 Super Key: A super key is a group of single or multiple keys which identifies rows in
a table.
 Primary Key: A column or group of columns in a table that uniquely identify every
row in that 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.

Types of Integrity Constraints


 Key constraint
 Domain constraint
 Entity Integrity constraint
 Referential Integrity constraint

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

3. Entity integrity constraints


 The entity integrity constraint states that primary key value can't be null.
 This is because the primary key value is used to identify individual rows in relation
and if the primary key has a null value, then we can't identify those rows.
 A table can contain a null value other than the primary key field.

4. Referential Integrity Constraints


 A referential integrity constraint is specified between two tables.
 In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary
Key of Table 2, then every value of the Foreign Key in Table 1 must be null or be
available in Table 2.
Example:

---------------------------------------------------------------------------------------------------------------------

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 DATABASE 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));

 DESC Statement (Describe Table):


SQL DESC statement use for describe the list of column definitions for specified table. You
can use either DESC or DESCRIBE statement.
Syntax:
Describe table_name;
Example:

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.

 ALTER TABLE - ADD Column


To add a column in a table.
Syntax:
ALTER TABLE table_name ADD column_name datatype;
Example:
The following SQL adds an "Email" column to the "Persons" table:
ALTER TABLE Persons ADD Email varchar(255);datatype;

18
(MR23-1CS0103) Stack Development Frameworks Unit_02

Add Multiple Column in table:


ALTER TABLE table_name ADD ( column_name1
datatype[(size)],column_name2 datatype[(size)], ... );
 ALTER TABLE - DROP COLUMN
It is used to delete a column in a table
Syntax:
ALTER TABLE table_name DROP COLUMN column_name;
Example:
The following SQL deletes the "Email" column from the "Persons" table:
ALTER TABLE Persons DROP COLUMN Email;
 MODIFY EXISTING COLUMN IN TABLE
To change the data type of a column in a table
Syntax:
ALTER TABLE table_name MODIFY COLUMN column_name datatype;

 RENAME THE EXISTING COLUMN IN A TABLE


Syntax:
ALTER table table_name change old_column_name new_column_name datatype;
Example:
ALTER table persons change city district varchar(50);
 RENAME:
RENAME command is used to set a new name for any existing table.
Syntax (Rename Table):
RENAME TABLE old_table_name to new_table_name;

Example:
RENAME TABLE persons to students_info;

The above query will rename the table student 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;

 DROP TABLE / DATABASE


The DROP TABLE / DATABASE statement is used to drop an existing table in a database or
a database.

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

INSERT into person values (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);

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

UPDATE person SET ADDRESS = “LONDON” WHERE ID = 5;

Now, the PERSON table would have the following records,

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;

Now, the PERSON table would have the following records,


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | ram | 32 | LONDON | 5000 |
| 2 | sam | 28 | LONDON | 5000 |
| 3 | Henry | 30 | LONDON | 5000 |
| 4 | Adam | 29 | LONDON | 5000 |
| 5 | Alice | 25 | LONDON | 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.

DELETE FROM person


WHERE ID = 5;

Now, the person table would have the following records.


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | ram | 32 | LONDON | 5000 |
| 2 | sam | 28 | LONDON | 5000 |
| 3 | Henry | 30 | LONDON | 5000 |
| 4 | Adam | 29 | LONDON | 5000 |
+----+----------+-----+-----------+----------+

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,

SELECT * FROM person

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

To fetch selected fields (ID, NAME) of the table,

SELECT ID, NAME FROM person

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

• To enable the auto-commit: SET autocommit = 1;

• To turn-off the auto-commit: SET autocommit = 0;

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

 Syntax: SAVEPOINT savepoint_name;

 RELEASE SAVEPOINT
 The RELEASE SAVEPOINT statement deletes the specified savepoint.

 Syntax: RELEASE SAVEPOINT savepoint_name;

 ROLLBACK
 Rollback is used to restore the database to that state which was last committed.

 Syntax: ROLLBACK;

 Rollback the transaction to the savepoint.

 Syntax: ROLLBACK TO SAVEPOINT mysavepoint;

---------------------------------------------------------------------------------------------------------------------

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.

 Syntax: GRANT privilege_list


ON Object_name
TO user_name;
 REVOKE
 It is employed to remove a privilege from a user.
 REVOKE helps the owner to cancel previously granted permissions.

 Syntax: REVOKE privilege_list


ON Object_name
TO user_name;
---------------------------------------------------------------------------------------------------------------------
Joins
 SQL Join statement is used to combine data or rows from two or more tables based on
a common field between them.
 When the related data is stored across multiple tables, joins help you to retrieve
records combining the fields from these tables using their foreign keys.

Types of joins in SQL


SQL provides various types of Joins that are categorized based on the way data across
multiple tables are joined together. They are listed as follows −
 Inner Join
INNER JOIN is the default join which retrieves the intersection of two tables. It
compares each row of the first table with each row of the second table. If the pairs of these
rows satisfy the join-predicate, they are joined together.
SELECT columns_from_both_tables
FROM table1
INNER JOIN table2
ON table1.column1 = table2.column2
24
(MR23-1CS0103) Stack Development Frameworks Unit_02

 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

 Full Outer Join


The SQL FULL OUTER 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 both of the tables.
SELECT columns
FROM table1
FULL OUTER JOIN table2
ON table1.column1 = table2.column2;
---------------------------------------------------------------------------------------------------------------------
Triggers
 A trigger is a stored procedure in a database that automatically invokes whenever a
special event in the database occurs.
 A database that has a set of associated triggers is called an active database. A trigger
description contains three parts:
o Event: A change to the database that activates the trigger.
o Condition: A query or test that is run when the trigger is activated.
o Action: A procedure that is executed when the trigger is activated and its
condition is true.
 Triggers are written to be executed in response to any of the following events.
 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
 Triggers could be defined on the table, view, schema, or database with which the
event is associated.

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

 Row Level Triggers


 It fires for each record that was affected by the execution of DML statements
such as INSERT, UPDATE, DELETE, and so on.
 A FOR EACH ROW clause is always used in a triggering statement.
 Statement Level Triggers
 It fires once for each executed statement.

 Event Triggers
Event triggers are divided into three parts:

27
(MR23-1CS0103) Stack Development Frameworks Unit_02

 DDL Event Trigger


 It is triggered by the execution of every DDL statement (CREATE, ALTER,
DROP, TRUNCATE).
 DML Event Trigger
 It is triggered by the execution of every DML statement (INSERT, UPDATE,
DELETE).
 Database Event Trigger
 It is triggered by the execution of any database operation, such as LOGON,
LOGOFF, SHUTDOWN, SERVERERROR, and so on.

 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

 Preferably, an index must be created on column(s) of a large table that are


frequently queried for data retrieval.

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

CREATE INDEX index_name ON table_name (column_name);

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

CREATE INDEX index_name on table_name (column1, column2);

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 −

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE [condition];
Example:
CREATE VIEW studentview AS SELECT
NAME, ADDRESS FROM StudentDetails
WHERE S_ID < 5;

 Syntax to fetch the view table


select column_name from view_name;

 Syntax to delete the view


DROP view view_name;

 Syntax to update the view

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

1. Explain in detail about different levels of schema in DBMS.


2. Discuss in detail about different types of data models?
3. Define database. Give an overview of database architecture.
4. Explain various integrity constraint in SQL with example.
5. List and explain various DDL commands in SQL with examples.
6. List and explain various DML commands in SQL with examples.
7. What do you mean by JOINs? Explain different types of JOINs?
8. What is trigger? Explain how to implement triggers in SQL?
9. What is a view in SQL? Write a syntax for creating views with an example.
10. Write about SQL Indexes and explain various types of Indexes.

31
(MR23-1CS0103) Stack Development Frameworks Unit_03

Unit_03 - Django Frameworks


Introduction
 Django is a back-end server side web framework and it is free, open source and
written in Python.
 A web framework is a software that supports the development of dynamic websites,
applications, and services. It provides a set of tools and functionalities that solves
many common problems associated with web development, such as security
features, database access, sessions, template processing, URL routing,
internationalization, localization, and much more.

Django Architecture
 Django web framework follows the MVT (Model View Template) architecture.
 This architectural pattern is designed for easy and rapid web development.

Fig: MVT based control flow

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.

Communication of components in MVT Architecture:


 First, a user requests for a resource. Django considers the request as a URL and
matches it with the existing URL paths in the urls.py file.
 This process of matching the user-requested URL to the one in urls.py is known as
URL mapping. Once the URL matches, Django carries out the further process.
 Once the URL is mapped, Django jumps to the views.py folder and calls a view.
 The triggered view looks for models and templates to interact with, and then it
returns the response back to the user. Here, the model deals with the data associated
with the user request.
 On the other hand, the template deals with the HTML and the static files, such as
CSS files, JS files, images, etc., that are required to complete the view.

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

 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.
--------------------------------------------------------------------
Web Server
 A web server is software and hardware that uses HTTP (Hypertext-Transfer-
Protocol) and other protocols to respond to client requests made over the World
Wide Web. The main job of a web server is to display website content through
storing, processing and delivering webpages to users.
 However, web servers can serve static as well as dynamic contents. Web Servers also
assists in emailing services and storing files. Therefore it also uses SMTP (Simple
Mail Transfer Protocol) and FTP (File Transfer Protocol) protocols to support the
respective services. Web servers are mainly used in web hosting or hosting the
website's data and running web-based applications.
 The hardware of the web servers are connected to the Internet that manages the data
exchange facility within different connected devices. In contrast, the software of web
server software is responsible for controlling how a user accesses delivered files.
Typically, web server management is an ideal example of the client/server model.
Therefore, it is compulsory for all computers that host websites (whether with state
or dynamic web page content) to have web server software.
 At the most basic level, whenever a browser needs a file that is hosted on a web
server, the browser requests the file via HTTP. When the request reaches the correct
(hardware) web server, the (software) HTTP server accepts the request, finds the
requested document, and sends it back to the browser, also through HTTP. (If the
server doesn't find the requested document, it returns a 404 response instead.)

To publish a website, you need either a static or a dynamic web server.


 A static web server, or stack, consists of a computer (hardware) with an HTTP
server (software). We call it "static" because the server sends its hosted files as-is
to your browser.
 A dynamic web server consists of a static web server plus extra software, most
commonly an application server and a database. We call it "dynamic" because the

3
(MR23-1CS0103) Stack Development Frameworks Unit_03

application server updates the hosted files before sending content to your
browser via the HTTP server.

How do web servers work?


The term web server can denote server hardware or server software, or in most cases,
both hardware and software might be working together.
1. On the hardware side, a web server is defined as a computer that stores software
and another website raw data, such as HTML files, images, text documents, and
JavaScript files. The hardware of the web servers are connected to the web and
supports the data exchange with different devices connected to the Internet.
2. On the software side, a web server includes server software accessed through
website domain names. It controls how web users access the web files and
ensures the supply of website content to the end-user. The web server contains
several components, including an HTTP server.
Whenever any web browser, such as Google Chrome, Microsoft Edge or Firefox,
requests for a web page hosted on a web server, the browser will process the request
forward with the help of HTTP. At the server end, when it receives the request,
the HTTP server will accept the request and immediately start looking for the requested
data and forwards it back to the web browser via HTTP.
Let's discover the step-by-step process of what happens whenever a web browser
approaches the web server and requests a web file or file. Follow the below steps:
1. First, any web user is required to type the URL of the web page in the address
bar of your web browser.
2. With the help of the URL, your web browser will fetch the IP address of your
domain name either by converting the URL via DNS (Domain Name System) or
by looking for the IP in cache memory. The IP address will direct your browser
to the web server.
3. After making the connection, the web browser will request for the web page
from the web server with the help of an HTTP request.
4. As soon as the web server receives this request, it immediately responds by
sending back the requested page or file to the web browser HTTP.
5. If the web page requested by the browser does not exist or if there occurs some
error in the process, the web server will return an error message.
6. If there occurs no error, the browser will successfully display the webpage.
--------------------------------------------------------------------
Installing & Configuring Django Components

 Django is a Python web framework, thus requiring Python to be installed on


machine.
 We can download python from the following website: https://www.python.org/
 Download the executable installer and run it. Check the boxes next to “Install
launcher for all users (recommended)” then click “Install Now”.
 Open PyCharm and Click on New Project.

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

 Start a project by using following command-


django-admin startproject Myproject
 Change directory to Myproject.
cd Myproject
 Start the server by typing the command
python manage.py runserver
By clicking the link http://127.0.0.1:8000/ we can see the result.

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.

Step 4: Start a project by using following command-


django-admin startproject Myproject
Step 5: Change directory to Myproject.
cd Myproject
Step 6: Create the application by using following command
Python manage.py startapp myapp

Create views.py and write the following code:


from django.shortcuts import render
from django.http import HttpResponse

6
(MR23-1CS0103) Stack Development Frameworks Unit_03

def myview(request):
return HttpResponse("Hello world!")

Create the urls.py and write the following code


from django.urls import path

from .views import myview

urlpatterns = [
path("",myview, name="home"),
]

Update the Myproject urls.py with the following code,


from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path("", include("polls.urls")),
]

Step 7: Start the server by typing following command in cmd–


python manage.py runserver
By clicking the link http://127.0.0.1:8000/ we can see the result.

--------------------------------------------------------------------

Creating views and Mapping URLs in Django


7
(MR23-1CS0103) Stack Development Frameworks Unit_03

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.

views.py (in application directory)


from django.http import HttpResponse

def myview(request):
text = """<h1>welcome to my app !</h1>"""
return HttpResponse(text)

 First, we import the class HttpResponse from the django.http module


 Next, we define a function called myview. This is the view function. Each view
function takes an HttpRequest object as its first parameter, which is typically named
request.
 The view returns an HttpResponse object that contains the generated response. Each
view function is responsible for returning an HttpResponse object.

Create a file urls.py


To access that view via a URL. Django has his own way for URL mapping and it's done
by editing your project url.py file.
from django.contrib import admin
from django.urls import path, include

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

Then create urls.py in application directory and map views


from django.urls import path

# importing views from views.py


from .views import myview

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.

url mapping is composed of three elements −


 The pattern − A regexp matching the URL you want to be resolved and map.
Everything that can work with the python 're' module is eligible for the pattern.
 The python path to the view − Same as when you are importing a module.
 The name − In order to perform URL reversing, you’ll need to use named URL
patterns as done in the examples above. Once done, just start the server to access
your view via http://127.0.0.1/8000.
--------------------------------------------------------------------
Template
 Being a web framework, Django needs a convenient way to generate HTML
dynamically. The most common approach relies on templates.
 A template contains the static parts of the desired HTML output as well as some
special syntax describing how dynamic content will be inserted.
 A Django project can be configured with one or several template engines.
 Django ships built-in backends for its own template system, creatively called the
Django template language (DTL), and for the popular alternative Jinja2.
 Django defines a standard API for loading and rendering templates regardless of
the backend.
 Loading consists of finding the template for a given identifier and preprocessing it,
usually compiling it to an in-memory representation.
 Rendering means interpolating the template with context data and returning the
resulting string.

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

Update the Settings.py


Open the settings.py in project directory.
Look up the INSTALLED_APPS[ ] list and add the our app.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]

Find the DIRS[ ] and update with the following code,


'DIRS': [os.path.join(BASE_DIR, 'template')],

Start the server by typing following command in cmd–


python manage.py runserver
By clicking the link http://127.0.0.1:8000/ we can see the result.

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

 Variable names can be any combination of alphanumeric characters and the


underscore (“_”) but may not start with an underscore, and may not be a number.
You also cannot have spaces or punctuation characters in variable names.

Create a file course.html


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewpoint" content="width=device-
width,initial-scale=1.0">
<title>Django</title>
</head>
<body>
<h1>Name: {{nm}}</h1>
<h1>Duration: {{du}}</h1>
<h1>Total Seats: {{st}}</h1>
</body>
</html>

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:

Create a View Function

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

from django.http import HttpResponse


from django.template import loader

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.

 An important goal of the DRY principle is to improve the maintainability of code


during all phases of its lifecycle. When the DRY principle is followed, for example, a
software developer should be able to change code in one place, and have the change
automatically applied to every instance of the code in question.

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

Unit_04 – Forms, User Input, Authentication and User


Management
Building forms using Django's
 Django provides a Form class which is used to create HTML forms. It describes a
form and how it works and appears.
 It is similar to the ModelForm class that creates a form by using the Model, but it
does not require the Model.
 Each field of the form class map to the HTML form <input> element and each one is
a class itself, it manages form data and performs validation while submitting the
form.
 Django’s form functionality can simplify and automate vast portions of work like
prepared for display in a form, rendered as HTML, edit using a convenient interface,
returned to the server, validated and cleaned up etc. and can also do it more
securely than most programmers would be able to do in code they wrote
themselves.

Django handles three distinct parts of the work involved in forms:


 Preparing and restricting data to make it ready for rendering
 Creating HTML forms for the data
 Receiving and processing submitted forms and data from the client.

 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

A “StudentRegistration” form is created that contains two fields


 Charfield is a class and used to create an HTML text input component in the
form.
 Emailfield is a class and used to create an Email Input component in the form.

Now, we need to instantiate the form in views.py file. See, the below code.
views.py

from django.shortcuts import render


from .forms import StudentRegistration
# Create your views here.
def showformdata(request):
fm = StudentRegistration()
return render(request, 'userregister.html',
{'form': fm})

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

from django import forms

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.

Default Widget in Form Fields


 Every field has a predefined widget, for example IntegerField has a default
widget of NumberInput.

Custom Django form field widgets


 The default widget can be override for various purposes. We must specifically
declare the widget we wish to attach to a field in order to override the default
one.

Example

5
(MR23-1CS0103) Stack Development Frameworks Unit_04

from django import forms


class StudentRegistration(forms.Form):
title = forms.CharField(widget = forms.Textarea)
description = forms.CharField(widget = forms.CheckboxInput)
views = forms.IntegerField(widget = forms.TextInput)
date = forms.DateField(widget=forms.SelectDateWidget)

Now, we need to instantiate the form in views.py file. See, the below code.
views.py

from django.shortcuts import render


from .forms import StudentRegistration
# Create your views here.
def showformdata(request):
fm = StudentRegistration()
return render(request, 'userregister.html', {'form':
fm})

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

from django import forms

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,

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

CREATE READ UPDATE DELETE


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

The INSERT statement is used for CREATE:


INSERT INTO <table name> VALUES (field value 1, field
value, 2…)
 The SELECT statement is used for READ:
SELECT field 1, field 2, …FROM <table name> [WHERE
<condition>]
 The UPDATE statement is used for UPDATE:
UPDATE <table name> SET field1=value1, field2=value2,…
[WHERE <condition>]
 The DELETE statement is used for DELETE:
DELETE FROM <table name> [WHERE <condition>]
 CRUD operations in NoSQL databases will depend on the language of the specific
database platform.
 CREATE
db.collection.insertOne()or db.collection.insertMany().
 READ
db.collection.find() or db.collection.findOne().
 UPDATE
db.collection.updateOne(), db.collection.updateMany() , or
db.collection.replaceOne().
 DELETE
db.collection.deleteOne() or db.collection.deleteMany().
--------------------------------------------------------------------
Implementing user registration and authentication
 Django comes with a user authentication system. It handles user accounts, groups,
permissions and cookie-based user sessions.
 Django authentication provides both authentication and authorization together and
is generally referred to as the authentication system.
 The authentication system consists of:
 Users
 Permissions: Binary (yes/no) flags designating whether a user may perform a
certain task.
 Groups: A generic way of applying labels and permissions to more than one
user.
 A configurable password hashing system
 Forms and view tools for logging in users, or restricting content

10
(MR23-1CS0103) Stack Development Frameworks Unit_04

 A pluggable backend system


 The authentication system in Django aims to be very generic and doesn’t provide
some features commonly found in web authentication systems. Solutions for some
of these common problems have been implemented in third-party packages:
 Password strength checking
 Throttling of login attempts
 Authentication against third-parties
 Object-level permissions

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

 Besides the SESSION_ENGINE, Django allows you to customize sessions with


specific settings. The following table list the most important ones:
Session settings Description
SESSION_COOKIE_AGE The duration of session cookies in session.
SESSION_COOKIE_DOMAIN Set the domain for session cookies.
SESSION_COOKIE_HTTPONLY Set to True to prevent JavaScript from accessing
the session cookie. It defaults to True, which
increases security against user session
hijacking.
SESSION_COOKIE_SECURE Set to True to indicate that the cookie should
only be sent if the connection is an HTTPS
connection. It defaults to False.
SESSION_EXPIRE_AT_BROWSER_CLOSE Set to True to expire the session when you close
the browser. Its default value is False. If you set
this to True, the SESSION_COOKIE_AGE
won’t have any effect.
SESSION_SAVE_EVERY_REQUEST Set to True to save the session and update
session expiration to the database on every
request. It defaults to False.

--------------------------------------------------------------------

Building user profiles and account management


Django’s built-in authentication system is automatically added to the admin interface
when the project have been started.
With the admin we can:
 Add, edit and Delete Users
 Reset user passwords
 Assign Staff and/or Superuser status to a user
 Add or remove user permissions
 Create user groups; and
 Add users to a group
Add a User
 In order to log into the admin site, we need a user account with Staff status enabled.
 In order to view and create records we also need this user to have permissions to
manage all our objects.
 We can create a "superuser" account that has full access to the site and all needed
permissions using manage.py.
 Call the following command, in the same directory as manage.py, to create the
superuser. You will be prompted to enter a username, email address,
and strong password.
python manage.py createsuperuser

14
(MR23-1CS0103) Stack Development Frameworks Unit_04

Which will give this prompt:


Username:
Here you must enter: username, e-mail address and password:
Username: johndoe
Email address: [email protected]
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]:
My password did not meet the criteria, but this is a test environment, and I choose to
create user anyway, by enter y:
Bypass password validation and create user anyway? [y/N]: y
If you press [Enter], you should have successfully created a user:
Superuser created successfully.
Now start the server again:
py manage.py runserver
In the browser window, type 127.0.0.1:8000/admin/ in the address bar.
And fill in the form with the correct username and password:

Which should result in this user interface:

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

Adding User Permissions


 Permissions are used to control access to specific resources or actions within an
application, and authorization is the process of checking whether a user has the
necessary permissions to access a resource or perform an action.
 The ModelAdmin class in Django provides methods for setting permissions on a
per-object basis, in addition to the default permissions set on the model as a whole.
 By overriding these methods in a custom ModelAdmin class, you can specify
custom logic for determining whether a user has permission to view, add, change,
or delete a specific object instance.
 This allows for fine-grained control over permissions and can be useful in situations
where the standard model-level permissions are not sufficient.
Default permissions
 When django.contrib.auth is included in the INSTALLED_APPS setting, it
automatically creates four default permissions for each model defined in your
installed applications:
 add: Allows a user to create new instances of a model.
 change: Allows a user to update existing instances of a model.

16
(MR23-1CS0103) Stack Development Frameworks Unit_04

 delete: Allows a user to delete existing instances of a model.


 view: Allows a user to view existing instances of a model.
 These permissions are created when you run the command "python manage.py
makemigrations" and are stored in the database.
 These permissions can be assigned to a user or group via Django's built-in admin
interface or programmatically.
Groups
 The Group model provided by django.contrib.auth is a way to organize users into
groups and assign permissions or other labels to those groups.
 Each group can have any number of users associated with it, and a user can belong
to multiple groups.
 When a user is added to a group, they automatically inherit the permissions that
have been granted to that group. This is one of the key features of the Group model
and allows you to easily manage permissions for multiple users at once.
 For example, if you have a group named "blog editors" and you have granted the
permission "can_edit_blog_page" to that group, any user that belongs to that group
will have the ability to edit the blog page.
--------------------------------------------------------------------
Review Questions
1. How to create a form using Django Forms? Explain with example.
2. Discuss in detail about Django form validation.
3. Explain Django Form Widget with example.
4. Brief about handling form errors in django.
5. Identify and explain the Django CRUD operations.
6. Explain in detail about user authentication in Django.
7. How to manage the user sessions and permissions in Django?
8. Discuss in detail about building user profiles and account management.

17
(MR23-1CS0103) Stack Development Frameworks Unit_05

Unit_05 – RESTful APIs with Django Rest Framework


REST architecture
 REST, or REpresentational State Transfer, is an architectural style for providing
standards between computer systems on the web, making it easier for systems to
communicate with each other.
 REST-compliant systems, often called RESTful systems, are characterized by how
they are stateless and separate the concerns of client and server.
 REST is not a standard but a set of architectural principles that guide the design of
web services. Representational State Transfer is known for its simplistic nature, and
utilizes interactions in order to communicate via HTTP protocols.

A Restful system consists of a:


 client who requests for the resources.
 server who has the resources.

 It is important to create REST API according to industry standards which results in


ease of development and increase client adoption.

Architectural Constraints of RESTful API: There are six architectural constraints


which makes any web service are listed below:
 Uniform Interface
 Stateless
 Cacheable
 Client-Server
 Layered System
 Code on Demand
 Uniform Interface: It is a key constraint that differentiate between a REST API and
Non-REST API. It suggests that there should be an uniform way of interacting with
a given server irrespective of device or type of application (website, mobile app).
There are four guidelines principle of Uniform Interface are:
 Resource-Based: Individual resources are identified in requests. For example:
API/users.
 Manipulation of Resources Through Representations: Client has
representation of resource and it contains enough information to modify or
delete the resource on the server, provided it has permission to do so. Example:
Usually user get a user id when user request for a list of users and then use that
id to delete or modify that particular user.
 Self-descriptive Messages: Each message includes enough information to
describe how to process the message so that server can easily analyses the
request.

1
(MR23-1CS0103) Stack Development Frameworks Unit_05

 Hypermedia as the Engine of Application State (HATEOAS): It need to


include links for each response so that client can discover other resources
easily.

 Statelessness: A RESTful API should be stateless. In simple words, it means that it


doesn’t store any information about the user’s session. Therefore, every single
request should provide complete data to process it. Thus, it leads to greater
availability of the API.
 Cacheability: The server’s response should provide information on whether it
should be cached and for what time or not. Caching the data that updates rarely
improves performance and eliminates redundant client-server interactions.
 Client-server architecture: The client uses URIs to obtain resources. It doesn’t
concern how the server process the request. On the other hand, the server process
and returns the resources. It doesn’t impact a user interface in any way. Both client
and server don’t need to know about other responsibilities. Thus, they can evolve
independently. It allows using a single API in many different clients, e.g., web
browsers, mobile apps.
 Layered system: A REST API can consist of multiple layers, eg., business logic,
presentation, data access. Moreover, layers shouldn’t directly impact others.
Further, the client shouldn’t know if it’s connected directly to the end server or
intermediary. Therefore, we can easily scale the system or provide additional
layers such as gateways, proxies, load balancers.
 Code on demand: This one is an optional constraint. The server can return a part
of the code itself instead of the data in JSON format. The point is to provide
specific operations on the data that the client can use directly. Although, it’s not a
common practice.
--------------------------------------------------------------------

Setting up Django REST Framework


 Django is a Python web framework, thus requiring Python to be installed on
machine.
 We can download python from the following website: https://www.python.org/
 Download the executable installer and run it. Check the boxes next to “Install
launcher for all users (recommended)” then click “Install Now”.
 Open PyCharm and Click on New Project.

 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

 Start a project by using following command-


django-admin startproject Myproject
 Change directory to Myproject.
cd Myproject
 Start the server by typing the command
python manage.py runserver
By clicking the link http://127.0.0.1:8000/ we can see the result.

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',
]
--------------------------------------------------------------------

Build Web API using Django REST


 Steps to Create a REST API Using Django REST Framework

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: Open the terminal in pycharm and type the following command to install
Django
pip install django

Step 4: Type the following Command in pycharm Terminal to install Django REST
Framework.
pip install djangorestframework

Step 5: Start a project by using following command-


django-admin startproject Myproject

4
(MR23-1CS0103) Stack Development Frameworks Unit_05

Then change directory to Myproject.


cd Myproject

Step 6: Start the application by using following command-


python manage.py startapp myapp

Step 7: Add 'rest_framework' and ‘application name (myapp) to your


INSTALLED_APPS setting (in setting.py).
INSTALLED_APPS = [
...
'rest_framework',
'mpapp',
]
Register the app URLs of “myapp” in the urls.py file:

from django.contrib import admin


from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]

Creating a REST API View


 In order to prevent errors, add a dummy view to the views.py file of the app. From
the Django REST framework, you first have to import the @apiview decorator and
Response object.
 This is because @apiview displays the API while Response returns sterilized data in
JSON format.

@api_view(['GET'])
def getData(request):
person = {'name':'Denny','age':'25'}
return Response(person)

Building a URL Path for the App

from django.urls import path


from . import views
from django.conf import settings

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.

How RESTful APIs work


 A RESTful API breaks down a transaction to create a series of small modules.
 Each module addresses an underlying part of the transaction.

6
(MR23-1CS0103) Stack Development Frameworks Unit_05

 This modularity provides developers with a lot of flexibility, but it can be


challenging for developers to design their REST API from scratch.
 To understand how REST APIs work, it is critical to understand resources. A
resource can be any information that could be named, such as a document or image,
a collection of other resources, a non-virtual object, and more. Meanwhile, REST
uses a resource identifier to recognize the specific resource involved in an
interaction between components.
 The method is the type of request you send to the server. The four main resource
methods that are associated with REST APIs are:
 GET: This method allows for the server to find the data you requested and
sends it back to you.
 PUT: If you perform the ‘PUT’ request, then the server will update an entry in
the database.
 POST: This method permits the server to create a new entry in the database.
 DELETE: This method allows the server to delete an entry in the database.

 RESTful principles - RESTful APIs adhere to constraints around having a uniform


interface, being stateless, exposing directory structure-like URIs, and transferring
XML, JSON or other representations of resources.
 Resource Identification - Every entity that can be manipulated or accessed in the
API is represented as an HTTP resource exposed at a URI endpoint. URIs identify
collections, elements, attributes etc.

 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

How does an API Endpoint work?


 An endpoint in the context of an API (Application Programming Interface) is a
specific URL linking to a particular resource. When interacting with an API,
endpoints can execute specific activities like requesting data or triggering a process.
 Consider an API for user management containing the following endpoints:

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

Endpoints with Multiple Protocols


 An endpoint is essentially a combination of a URL and an HTTP method.
 The HTTP method defines the type of operation supported by that endpoint. An
endpoint can therefore support multiple protocols by allowing different HTTP
methods.
 For instance, consider an endpoint /users representing a collection of users in an
API. This endpoint could support the following protocols:
 HTTP GET: Retrieves all the users from the collection using the HTTP GET
technique
 HTTP POST: We can add a new user to the collection using the HTTP POST
technique
 HTTP PUT: Update the full collection of users using the HTTP PUT technique
(i.e., replacing it with a new collection)

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.

Practices for designing and developing API endpoints


 API endpoints are essential to the performance of any application. The following
best practices can help to design, develop, and maintain endpoints that are reliable,
scalable, user-friendly, and secure.
1. Create a predictable and intuitive API endpoint structure
It’s important to use a clear and intuitive naming convention and structure when
defining your API’s endpoints. When possible, the same conventions should apply to
every API in your digital portfolio.
2. Implement secure authentication mechanisms
API endpoints are the doorways to an application’s data, which makes them
appealing attack targets. API authentication involves verifying the identity of a client
that is making an API request, and it plays a crucial role in strengthening an API’s
security posture. It’s therefore important to leverage well-established authentication
mechanisms especially if the endpoints provide access to sensitive data.
3. Validate and sanitize input data
Input validation is the process of confirming that any data that’s sent to the API
follows the expected format and constraints, while sanitization helps ensure that input
data does not include harmful characters in order to prevent any malicious code.
4. Clearly document every API endpoint
Private API documentation facilitates cross-team collaboration and reduces code
duplication, while public API documentation helps potential consumers understand
and experiment with an API.
5. Continually test and monitor your API endpoints
API testing helps ensure that an API’s endpoints work as expected—even as the API
evolves. Unit tests confirm that a single endpoint returns the correct response to a given
request, while end-to-end tests validate complex workflows that may involve multiple
endpoints. API test automation can help team’s automatically surface issues throughout
the development process.
--------------------------------------------------------------------

CRUD operation with Django REST Framework


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

9
(MR23-1CS0103) Stack Development Frameworks Unit_05

CRUD

CREATE READ UPDATE DELETE


 CREATE:
 CREATE operation adds a new record to a database.
 Create view will use the POST method for inserting data into our database.
@api_view(['POST'])
def add_items(request):
item = ItemSerializer(data=request.data)

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

Authentication in Django REST Framework


 Authentication is the mechanism of associating an incoming request with a set of
identifying credentials, such as the user the request came from, or the token that it
was signed with. The permission and throttling policies can then use those
credentials to determine if the request should be permitted.
 REST framework provides several authentication schemes out of the box, and also
allows you to implement custom schemes.
 Authentication always runs at the very start of the view, before the permission and
throttling checks occur, and before any other code is allowed to proceed.
 The request.user property will typically be set to an instance of
the contrib.auth package's User class.

 The request.auth property is used for any additional authentication information,


for example, it may be used to represent an authentication token that the request
was signed with.

11
(MR23-1CS0103) Stack Development Frameworks Unit_05

How authentication is determined


 The authentication schemes are always defined as a list of classes. REST framework
will attempt to authenticate with each class in the list, and will
set request.user and request.auth using the return value of the first class that
successfully authenticates.
 If no class authenticates, request.user will be set to an instance
of django.contrib.auth.models.AnonymousUser , and request.auth will be set
to None .
 The value of request.user and request.auth for unauthenticated requests can be
modified using the
UNAUTHENTICATED_USER and UNAUTHENTICATED_TOKEN settings.

 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

classes to include TokenAuthentication , and additionally


include rest_framework.authtoken in your INSTALLED_APPS setting.

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

 request.user will be a Django User instance.


 request.auth will be None .
 Unauthenticated responses that are denied permission will result in an HTTP 403
Forbidden response.

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.

 Creating responses with Response ()


 Signature: Response(data, status=None, template_name=None, headers=None,
content_type=None)
 Unlike regular HttpResponse objects, you do not instantiate Response objects
with rendered content. Instead you pass in unrendered data, which may consist
of any Python primitives.
 The renderers used by the Response class cannot natively handle complex
datatypes such as Django model instances, so you need to serialize the data into
primitive datatypes before creating the Response object.
 You can use REST framework's Serializer classes to perform this data
serialization, or use your own custom serialization.
 Arguments:
 data : The serialized data for the response.
 status : A status code for the response. Defaults to 200. See also status codes.
 template_name : A template name to use if HTMLRenderer is selected.
 headers : A dictionary of HTTP headers to use in the response.
content_type : The content type of the response. Typically, this will be set
automatically by the renderer as determined by content negotiation, but there
may be some cases where you need to specify the content type explicitly.
--------------------------------------------------------------------

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

You might also like