0% found this document useful (0 votes)
49 views22 pages

FSD Modulle-1

Uploaded by

Zuha Kareem
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)
49 views22 pages

FSD Modulle-1

Uploaded by

Zuha Kareem
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/ 22

GHOUSIA COLLEGE OF ENGINEERING (GCE)

Ramanagara - 562159.
(Affiliated to Visvesvaraya Technological University – VTU )

080-27273577 / +91-9559535257, [email protected]

Department of Computer Science and Engineering


VI- Semester

Subject : Fullstack Development


Subject code : (21CS62)
Ref: (https://django-book-
new.readthedocs.io/en/latest/license.html)

1
Module-1
MVC Based web designing
Web development refers to developing and maintaining websites
and web applications. It can be a single web page, either a static
or dynamic website or a web application.
Web framework: Web Application Framework or simply “web
framework” is a software framework that is designed to support
the development of web applications including web services, web
resources, and web APIs. Frameworks are, in short, libraries that
help you develop your application faster and smarter, and also
provides a programming infrastructure for your applications so
that you can focus on writing clean, maintainable code without
having to reinvent the wheel.
The web development frameworks can be divided into two:
Front-end frameworks and Back-end frameworks.
Front-End Frameworks
Frontend web development frameworks are used to create the
user interface of the website that is seen and used by the users.
They develop the client side of the application. Some of the
popular front-end web development frameworks are Angular and
Vue.js.
Back-End Frameworks
Backend web development frameworks are used on the server
side of the application. They provide backend functionalities
responsible for handling requests, databases, communicating
with APIs, etc. Some of the popular backend web development
frameworks are Ruby on Rails, Django, PHP, etc.
Advantages of Frameworks such as:
 Easy to test your code and debug it.
 Clean code is much easy to understand and work with.
 Reduces redundancy of code in the project.
 Reduces the time and cost of the project with the enhanced
application.
 Features and functionalities provided by the framework can
be modified and extended.
Popular Stacks

2
MEAN Stack: MongoDB, Express, AngularJS and Node.js.
MERN Stack: MongoDB, Express, ReactJS and Node.js
Django Stack: Django, python and MySQL as Database.
Rails or Ruby on Rails: Uses HTML,Ruby, Rails and MySQL.
LAMP Stack: Linux, Apache, MySQL and PHP.

Example that demonstrates the difference between the


previous approach and that undertaken using a Web
framework

Django is a prominent member of a new generation of Web


frameworks.
To answer that question, let’s consider the design of a Web
application written using the Common Gateway Interface
(CGI) standard, a popular way to write Web applications
around 1998
In those days, when we wrote a CGI application, we did
everything yourself. For example, here’s a simple CGI
script, written in Python, that displays the ten most recently
published books from a database:
#!/usr/bin/python
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"

connection = MySQLdb.connect(user='me',
passwd='letmein', db='my_db')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY
pub_date DESC LIMIT 10")
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
3
This code is straightforward. First, it prints a “Content-
Type” line, followed by a blank line, as required by CGI.
It prints some introductory HTML, connects to a database,
and executes a query that retrieves the latest ten books.
Looping over those books, it generates an HTML unordered
list.
Finally, it prints the closing HTML and closes the database
connection.
It’s simple to deploy: just save this code in a file called
latestbooks.cgi, upload that file to a Web server, and visit
that page with a browser.

But as a Web application grows beyond the trivial, this


approach breaks down, and we face a number of problems:
What happens when multiple pages need to connect to the
database? Surely that database connecting code shouldn’t
be duplicated in each individual CGI script, so the pragmatic
thing to do would be to refactor it into a shared function.

Should a developer really have to worry about printing the


“Content-Type” line and remembering to close the
database connection? This type of work reduces
programmer productivity and introduces opportunities for
mistakes. These setup- and teardown-related tasks would
best be handled by some common infrastructure.

“A Web framework provides a programming infrastructure


for your applications, so that you can focus on writing clean,
maintainable code without having to reinvent the wheel. In
a nutshell, that’s what Django does.”

4
MVC Design Pattern

MVC design pattern is also known as Model-View-


Controller. It is a common architectural pattern used to
design and create an application’s interfaces and structure.

5
This pattern divides the application into three parts that are
dependent and connected. These designs distinguish the
presentation of data from how the data is accepted by the
user to the data shown. These design patterns have
become common in the use of web applications and for
developing GUIs.
MVC defines a way of developing software so that the code for
defining and
accessing data (the model) is separate from request routing
logic (the controller), which in
turn is separate from the user interface (the view).

A key advantage of such an approach is that components are


loosely coupled. That is, each distinct piece of a Django-powered
Web application has a single key purpose and can be changed
independently without affecting the other pieces. For example,
a developer can change the URL for a given part of the
application without affecting the underlying implementation. A
designer can change a page’s HTML without having to touch the
Python code that renders it.
A database administrator can rename a database table and
specify the change in a single place, rather than having to search
and replace through a dozen files.

Django Evolution: Django is a prominent member of a


new generation of Web frameworks, Using Django, developer
can build and maintain high-quality Web applications with
minimal fuss. it provides high-level abstractions of common Web
development patterns, shortcuts for frequent programming
tasks, and clear conventions for how to solve problems. to
develop powerful Web sites quickly, with code that is clean and
easy to maintain.
Django is simply a collection of libraries written in the
Python programming language. To develop a site using Django,
you write Python code that uses these libraries.
Django grew organically from real-world applications
written by a Web development team in Lawrence, Kansas. It was
born in the fall of 2003, They released it in July 2005 and named
it Django, after the jazz guitarist Django Reinhardt.
6
Django was extracted from real-world code, rather than
being an academic exercise or commercial product, it is acutely
focused on solving Web development problems that Django’s
developers themselves have faced—and continue to face. As a
result, Django itself is actively improved on an almost daily
basis. The framework’s developers have a keen interest in
making sure Django saves developers time, produces
applications that are easy to maintain, and performs well under
load.

Evolution:
The classic Web developer’s path goes something like this:
1. Write a Web application from scratch.
2. Write another Web application from scratch.
3. Realize the application from step 1 shares much in
common with the application from step 2.
4. Refactor the code so that application 1 shares code with
application 2.
5. Repeat steps 2–4 several times.
6.Realize you’ve invented a framework

7
Django MVT (Model –View-Template)
 The MVT is a software design pattern which includes
three important components Model, View and
Template.
 The Model helps to handle database. It is a data access
layer which handles the data.
 The Template is a presentation layer which handles
User Interface part completely.
 The View is used to execute the business logic and
interact with a model to carry data and renders a
template.

Python Virtual EnvironmentTo create dynamic Web pages


with Django:
 A Python Virtual Environment is an isolated space
where you can work on your Python projects,
separately from your system-installed Python.
 You can set up your own libraries and dependencies
without affecting the system Python.
 There are no limits to the number of virtual
environments
 It allows you to have multiple Python environments
with different versions of Python and different sets of
installed packages on the same system.
 It is generally good to have one new virtual
environment for every Python-based project you work
on
8
 You can change the system python version, django
version and other dependencies without affecting the
project python version, django versions and
dependencies
Django project file structure with virtual env

Django File structure

Django project file structure

9
Django Application (App) File Structure

Dynamic Web page : the contents of the page are not


static; rather, the contents change according to the result of a
computation. To create a the page , developer need to write a
view function.
A View function, or view for short, is simply a Python
function that takes a Web request and returns aWeb response.
This response can be the HTML contents of aWeb page, or a
redirect, or a 404 error, or an XML document, or an image, The
view itself contains whatever arbitrary logic is necessary to

10
return that response. This code can live anywhere you want, as
long as it’s on your Python path.
Example todefine view function with current date time :
Here’s a view that returns the current date and time, as an
HTML document:
from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" %
now
return HttpResponse(html)
Let’s step through this code one line at a time:
 First, import the class HttpResponse, which lives in the
django.http module.
• Then we import the datetime module from Python’s
standard library, the set of useful modules that comes with
Python. The datetime module contains several functions and
classes for dealing with dates and times, including a function
that returns the current time.
• Define a function called current_datetime. This is the view
function. Each view function takes an HttpRequest object as
its first parameter, which is typically named request

How Django finds this function?


• The first line of code within the function calculates the current
date/time as a datetime.datetime object, and stores that as the
local variable now.
• The second line of code within the function constructs an HTML
response using Python’s format-string capability. The %s within
the string is a placeholder, and the percent sign after the string
means “Replace the %s with the value of the variable now.”
(Yes, the HTML is invalid, but we’re trying to keep the example
simple and short.)

11
• Finally, the view returns an HttpResponse object that contains
the generated response. Each view function is responsible for
returning an HttpResponse object.

Django Time Zone : Django includes a TIME_ZONE setting


that defaults to America/Chicago, you might want to
change it in your settings.py.

Dynamic URLS
In Django, URL patterns can capture various types of
parameters, such as
Integer: Captures an integer value from the URL.
path('<int:parameter>/', views.my_view)
String: Captures any string without a slash (/) from the URL.
path('<str:parameter>/', views.my_view)
Slug: Similar to a string, but typically used for URL slugs. It
allows alphabetic characters (a-z, A-Z), numbers (0-9),
underscores (_), and hyphens (-).
path('<slug:parameter>/', views.my_view)
Path: Captures a string containing slashes (/) from the URL.
Useful for capturing entire URL paths or file paths.

path('<path:parameter>/', views.my_view)

Mapping URLs to Views:


In Django, URL configurations, or URLconfs, serve as the "table
of contents" for your web application, mapping URL patterns to
corresponding view functions.

When you create a new Django project, a default URLconf is


generated in the file `urls.py`.

This file contains the `urlpatterns` variable, which Django uses


to determine which code to execute for a given URL.

Initially, the URLconf may be empty or have commented-out


examples, indicating a fresh project setup.
To activate a view, you need to uncomment or add a new URL
pattern in the `urlpatterns` list, ensuring that the view function
is accessible on the Python path.

12
This setup is crucial for Django to correctly render views when a
user navigates to a specific URL.

In the Django web framework, URL patterns are used to connect


URLs to views. In the provided code snippet, the
`current_datetime` view is connected to the URL pattern
`^time/$` using Django's `urlpatterns`.

This pattern will match any URL that exactly matches `/time/`,
due to the use of the caret (`^`) and dollar sign (`$`) which
anchor the pattern to the start and end of the string,
respectively.
The raw string notation (`r`) is used to avoid issues with escape
characters in the regular expression.
Raw String: r'^time/plus/(\d{1,2})/$'
Non-Raw String: '\\^time\\/plus\\/(\\d{1,2})\\/$' (more
complex and harder to read)
By passing the `current_datetime` function as an object to the
pattern, Django knows to execute this view function when the
specified URL is requested, demonstrating Python's capability of
treating functions as first-class objects.

13
How Django Processes a Request
1. Starting the Development Server
Command: python manage.py runserver
Imports settings.py containing crucial configurations, including
ROOT_URLCONF.
2. Configuration with settings.py
ROOT_URLCONF specifies the Python module for URLconf.
Automatically set to urls.py by default during project creation.
3. Request Processing
Incoming Request: For example, a request to /time/.
URLconf Loading: Django loads the module specified by
ROOT_URLCONF.
URL Pattern Matching:
Compares the requested URL against patterns defined in urls.py.
Continues until it finds a matching pattern.
4. Handling the Request
View Function Execution:
The matching URL pattern’s view function is called.
An HttpRequest object is passed to the view function.
Response Generation:
The view function processes the request.
Returns an HttpResponse object.

14
How Django Processes a Request : Complete Details

This diagram illustrates the flow of a request through the Django


framework, highlighting the sequence of steps and middleware
layers involved in processing an HTTP request from the browser
to the server and back.
1. Browser to Server:
 Browser: Initiates an HTTP request to the server.

15
 ModPythonHandler: Receives the HTTP request.
This is typically handled by a WSGI server in modern
Django setups, but the principle remains the same.
2. Request Processing:
HttpRequest: The request is converted into an HttpRequest
object.
Request Middleware: The request passes through a series
of middleware layers designed to process requests before
reaching the main URL routing. Middleware can modify the
request or return a response directly. If a response is returned
here, the process jumps to the response phase.
3. URL Routing:
URLConf: Django consults the URL configuration (urls.py)
to determine which view should handle the request. It matches
the URL pattern from the incoming request with the defined URL
patterns.
4. View Handling:
View Middleware: Before reaching the actual view, the
request can pass through additional middleware layers that
handle tasks such as authentication, caching, etc. If a response
is generated here, it skips directly to the response phase.
View: The matched view function is called, processing the
request and generating a response.
5. Response Processing:
Response Middleware: The response generated by the view
or middleware is passed back through a series of middleware
layers designed to process responses. These can modify the
response before it is sent back to the client.
6. Server to Browser:
HttpResponse: The processed response is sent back to the
browser as an HTTP response.
xception Handling:

16
Request Exception Handler: If an exception occurs during
the request phase, it is caught by this handler, which can
generate an appropriate error response.
View Exception Handler: If an exception occurs within the
view, it is caught here, which can also generate an appropriate
error response.
Exception Middleware: Specifically designed to catch
exceptions and provide error handling throughout the request-
response cycle.
404/500 Response: If no middleware or handler can handle
the exception, a standard 404 (Not Found) or 500 (Internal
Server Error) response is generated and sent to the client.

A URLconf is like a table of contents for your Django-


powered Web site. Basically, it’s a mapping between URL
patterns and the view functions that should be called for those
URL patterns.
URLconfs and Loose Coupling in Django:
Loose Coupling Principle:
Definition: Loose coupling emphasizes making software
components interchangeable, ensuring changes in one
component have minimal impact on others.
Django's URLconfs:
 Separation of Concerns: URL definitions and view
functions are kept separate.
 Example: Changing a URL (e.g., from /time/ to
/currenttime/) requires only an update to the URLconf,
not the view function.
 Flexibility: You can alter view functions or expose the
same functionality at multiple URLs by editing the
URLconf alone.
Comparison with Other Frameworks:

17
 Tight Coupling: Other platforms often tie URLs directly
to file paths or method names.
 PHP: URL is determined by file location.
 Early CherryPy: URL corresponds to method names.
 Drawbacks: This can lead to difficulties in managing
URLs and code in the long run.
Advantages of Loose Coupling in Django:
 Independent Changes: URL changes do not affect view
logic and vice versa.
 Enhanced Flexibility: Easily expose the same
functionality at different URLs without modifying the
core view code.

404 Errors in Django


Handling Undefined URLs:
Example URLs:

/hello/
/does-not-exist/
Site root (/)
Response: "Page not found" message
Details of the 404 Page:
 Information Provided:

18
 Indicates which URLconf was used
 Lists every pattern in the URLconf
Purpose: Helps developers understand
why the requested URL resulted in a 404
error.
Security Considerations:
Debug Mode:
404 page with detailed information is shown only in debug mode.
Intended for developers to troubleshoot.
Production Mode:
Debug mode should be deactivated.
A different, less informative response is shown to protect
sensitive information.
Default Behavior:
Initial State: Every new Django project starts in debug mode.

A Word About Pretty URLs in Django:


Pretty URLs: Clean, simple, and readable URLs are preferred in
Django.
Comparison:
 Query String Example: /time/plus?hours=3
 Pretty URL Example: /time/plus/3/
Advantages of Pretty URLs:
 Cleaner and simpler
 More readable
 Easier to communicate verbally
 Indicative of a quality web application
Django’s Approach:
Encouragement: Django’s URLconf system promotes the use of
pretty URLs by making them easier to implement than query
strings.
19
Philosophy:
Core Belief: URLs should be beautiful and enhance user
experience.
Django’s Pretty Error Pages
1. Introduction to Error Pages:
Purpose: Demonstrates Django's detailed error pages.
Example: Introduce a deliberate error in views.py by
commenting out offset = int(offset).
Example Error in Code:

Result: Navigating to /time/plus/3/ shows a TypeError.

Detailed Information on Error Page


Key Features of the Error Page:
 Exception Details:
 Type of exception
 Parameters (e.g., "unsupported type for timedelta hours
component: str")
 File and line number where the exception occurred

 Python Traceback:
 Full traceback with interactive frames
 Clickable lines to view surrounding code context
 "Local vars" to see local variables and their values at the
point of error

 Request Information:
 Details about the incoming web request: GET/POST data,
cookies, CGI headers
 Settings Section:
 Lists all settings for the Django installation

20
Using and Understanding Error Pages
Additional Features:
 Copy-and-Paste View:
Switch to an easily shareable version of the traceback for
technical support
 Debugging Tips:
Use assert False to trigger the error page and inspect local
variables and state without print statements
Security Considerations:
 Debug Mode:
Error pages with detailed information are shown only in
debug mode
Avoid exposing sensitive information on public sites
 Production Mode:
Deactivate debug mode to prevent exposure of sensitive
details
Wildcard URLpatterns :a wildcard in the URLpattern. As we
mentioned previously, a URLpattern is a regular expression;
hence, we can use the regular expression pattern \d+ to match
one or more digits:
from django.conf.urls.defaults import *
from mysite.views import current_datetime, hours_ahead
urlpatterns = patterns('',
(r'^time/$', current_datetime),
(r'^time/plus/\d+/$', hours_ahead),
)
This URLpattern will match any URL such as /time/plus/2/,
/time/plus/25/, or even /time/plus/100000000000/. Come to
think of it, let’s limit it so that the maximum allowed offset is
99 hours. That means we want to allow either one- or two-digit
numbers—in regular expression syntax, that translates into
\d{1,2}:
(r'^time/plus/\d{1,2}/$', hours_ahead), The designated a
wildcard for the URL, we need a way of passing that data to the
view function, so that we can use a single view function for any

21
arbitrary hour offset. We do this by placing parentheses around
the data in the URLpattern that we want to save. In the
case of our example, we want to save whatever number was
entered in the URL, so let’s put parentheses around the
\d{1,2}:(r'^time/plus/(\d{1,2})/$', hours_ahead), If you’re
familiar with regular expressions, you’ll be right at home here;
we’re using parentheses to capture data from the matched
text.
The final URLconf, including our previous current_datetime
view, looks like this:
from django.conf.urls.defaults import *
from mysite.views import current_datetime, hours_ahead
urlpatterns = patterns('',
(r'^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
)

22

You might also like