FSD Modulle-1
FSD Modulle-1
Ramanagara - 562159.
(Affiliated to Visvesvaraya Technological University – VTU )
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.
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.
4
MVC Design Pattern
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).
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.
9
Django Application (App) File Structure
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
11
• Finally, the view returns an HttpResponse object that contains
the generated response. Each view function is responsible for
returning an HttpResponse object.
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)
12
This setup is crucial for Django to correctly render views when a
user navigates to a specific URL.
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
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.
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.
/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.
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