0% found this document useful (0 votes)
11 views

FullStack-MODULE1

Uploaded by

manojhnacharya8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

FullStack-MODULE1

Uploaded by

manojhnacharya8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

FULL STAK DEVELOPMENT -21CS62

MODULE 1 - MVC Based Web Designing

eb Framework

A web framework is a code library that makes web development faster and easier by
providing common patterns for building reliable, scalable and maintainable web
applications.

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

The above code 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.
Drawbacks of using it is :
 Difficulty when multiple pages need to connect to the database

Navkis College of Engineering 1


FULL STAK DEVELOPMENT -21CS62

 Printing the “Content-Type” line and remembering to close the database connection
 Difficulty when the code is reused in multiple environments, each with a separate
database and password
 when a Web designer who has no experience coding Python wishes to redesign the
page
Web framework intends to solve all these problems. A Web framework provides a
programming infrastructure to the applications, so that clean, maintainable code can be
written without having to write it from the scratch.

MVC Design Pattern:

Example that demonstrates the difference between the previous approach and that undertaken
using a Web framework

Here the same CGI code is written using Django

Django is a free and open source web application framework which offers fast and effective
dynamic website development.

# models.py (the database tables)

from django.db import models


class Book(models.Model):
name = models.CharField(maxlength=50)
pub_date = models.DateField()

# views.py (the business logic)


from django.shortcuts import render_to_response
from models import Book
def latest_books(request):
book_list = Book.objects.order_by('-pub_date')[:10]
return render_to_response('latest_books.html', {'book_list': book_list})

# urls.py (the URL configuration)


from django.conf.urls.defaults import *
import views

Navkis College of Engineering 2


FULL STAK DEVELOPMENT -21CS62

urlpatterns = patterns('',
(r'latest/$', views.latest_books),
)

# latest_books.html (the template)


<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
<ul>
{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
</body></html>
• The models.py file contains a description of the database table, as a Python class. This is
called a model. Using this class, you can create, retrieve, update, and delete records in your
database using simple Python code rather than writing repetitive SQL statements
. • The views.py file contains the business logic for the page, in the latest_books() function.
This function is called a view.
• The urls.py file specifies which view is called for a given URL pattern. In this case, the
URL /latest/ will be handled by the latest_books() function.
• latest_books.html is an HTML template that describes the design of the page
these pieces loosely follow the Model-View-Controller (MVC) design pattern. Simply put,
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).
The MVT is a software design pattern which includes three important components Model,
View and Template.
Model: The Model helps to handle database. It is a data access layer which handles the data.
Template: The Template is a presentation layer which handles User Interface part
completely.
View: The View is used to execute the business logic and interact with a model to carry data
and renders a template.

Navkis College of Engineering 3


FULL STAK DEVELOPMENT -21CS62

Characteristics of Django:
1. Loosely Coupled − Django helps you to make each element of its stack independent
of the others.
2. Less code - Ensures effective development
3. Not repeated- Everything should be developed in precisely one place instead of
repeating it again
4. Fast development- Django's offers fast and reliable application development.
5. Consistent design - Django maintains a clean design and makes it easy to follow the
best web development practices.

Django Evolution:
 Django grew organically from real-world applications written by a Web development
team in Lawrence, Kansas. It was born in the fall of 2003
 In summer 2005, after having developed this framework to a point where it was
efficiently powering most of World Online’s sites, the World Online team, which now
included Jacob Kaplan-Moss, decided to release the framework as open source
software. They released it in July 2005 and named it Django, after the jazz guitarist
Django Reinhardt.
 Although Django is now an open source project with contributors across the planet,
the original World Online developers still provide central guidance for the
framework’s growth.

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

Navkis College of Engineering 4


FULL STAK DEVELOPMENT -21CS62

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.
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 = "It is now %s." % now
return HttpResponse(html)

 import the class HttpResponse, which is in the django.http module.


 Then import the datetime module from Python’s standard library . 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
 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.”
 Finally, the view returns an HttpResponse object that contains the generated response.
Each view function is responsible for returning an HttpResponse object

Mapping URLs to Views


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

Navkis College of Engineering 5


FULL STAK DEVELOPMENT -21CS62

from django.conf.urls.defaults import *


urlpatterns = patterns('',

# (r'^mysite/', include('mysite.apps.foo.urls.foo')),
# Uncomment this for admin:
# (r'^admin/', include('django.contrib.admin.urls')),
)
 The first line imports all objects from the django.conf.urls.defaults module, including
a function called patterns.
 The second line calls the function patterns() and saves the result into a variable called
urlpatterns. The patterns() function gets passed only a single argument—the empty
string. The rest of the lines are commented out.
Django expects the variable urlpatterns, to find the ROOT_URLCONF module. This
variable defines the mapping between URLs and the code that handles those URLs.
Let’s edit this file to expose our current_datetime view:

from django.conf.urls.defaults import *


from mysite.views import current_datetime
urlpatterns = patterns('',
(r'^cdt/$', current_datetime),
)

 There are two changes here. First, we imported the current_datetime view from its
module (mysite/views.py, which translates into mysite.views in Python import
syntax).
 Added the line (r'^time/$', current_datetime),. This line is referred to as a URLpattern
 it’s a Python tuple in which the first element is a simple regular expression and the
second element is the view function to use for that pattern.
 We passed the current_datetime view function as an object without calling the
function. This is a key feature of Python (and other dynamic languages): functions are
first-class object.
 The r in r'^time/$' means that '^time/$ is a Python raw string. This allows regular
expressions to be written without overly verbose escaping.

Navkis College of Engineering 6


FULL STAK DEVELOPMENT -21CS62

 You should exclude the expected slash at the beginning of the '^time/$' expression in
order to match /time/
 The caret character (^) and dollar sign character ($) are important. The caret means
“require that the pattern matches the start of the string,” and the dollar sign means
“require that the pattern matches the end of the string.”

To test the changes to the URLconf, start the Django development server by running the
command python manage.py runserver
 The server automatically detects changes done to Python code and reloads as
necessary.The server is running at the address http://127.0.0.1:8000/, so open up a
Web browser and go to http://127.0.0.1:8000/ time/. The output of the Django view
will display.
 After creating the wildcard for the URL,use a view function for any number of hour
offset.by placing the parenthesis around the data in the URLpattern.eg:parenthesis
around \d{1,2}: (r'^cdt/plus/(\d{1,2})/$', hours_ahead), it uses parentheses to capture
data from the matched text
The final URLconf, including current_datetime view is:

from django.conf.urls.defaults import *


from mysite.views import current_datetime, hours_ahead
urlpatterns = patterns('',
(r'^cdt/$', current_datetime),
(r'^cdt/plus/(\d{1,2})/$', hours_ahead),
)
Your Second View: Dynamic URLs
• In our first view example, the contents of the page—the current date/time—were
dynamic, but the URL (/time/) was static.
Example: Let’s create a second view that displays the current date and time offset by a
certain number of hours.
• To displays the date/time one hour into the future, page /time/plus/1/
• To displays the date/time two hour into the future, page /time/plus/2/
urlpatterns = patterns('',
(r'^time/$', current_datetime),

Navkis College of Engineering 7


FULL STAK DEVELOPMENT -21CS62

(r'^time/plus/1/$', one_hour_ahead),
(r'^time/plus/2/$', two_hours_ahead),
(r'^time/plus/3/$', three_hours_ahead),
(r'^time/plus/4//$', four_hours_ahead),
)
 In the First example,the contents of the page—the current_datetime—were dynamic,
but the URL (/cdt/) was static. In most dynamic Web applications, though, a URL
contains parameters that influence the output of the page
 Second view that displays the current date and time offset by a certain number of
hours. In such a way that the page /cdt/plus/1/ displays the date/time one hour into
the future, the page /cdt/plus/2/ displays the date/time two hours into the future, the
page /cdt/plus/3/ displays the date/time three hours into the future, and so on
 With that view function and URLconf written, start the Django development server (if
it’s not already running), and visit http://127.0.0.1:8000/cdt/plus/3/ to verify it works.
Then try http://127.0.0.1:8000/cdt/plus/5/.
 Then http://127.0.0.1:8000/cdt/plus/24/. Finally, visit
http://127.0.0.1:8000/cdt/plus/100/ to verify that the pattern in your URLconf only
accepts one- or two-digit numbers; Django should display a “Page not found” error in
this case. The URL http://127.0.0.1:8000/cdt/ plus/ (with no hour designation) should
throw a 404 Error.
Consider an example:
def hours_ahead(request, offset):
#offset = int(offset)
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body> in %s hour(s),it will be %s.<body></html>”% (offset, dt)
return HttpResponse(html)
The given view will display
TypeError message displayed at the very top: "unsupported type for timedelta hours
component: str".
Because the datetime.timedelta function expects the hours parameter to be an integer. That
caused datetime.timedelta to raise the TypeError

Working of Django (How Django Processes a Request)

Navkis College of Engineering 8


FULL STAK DEVELOPMENT -21CS62

When the Django development server starts running and makes requests to Web pages:
 The command python manage.py runserver imports a file called settings.py from
the same directory. This file contains all sorts of optional configuration for this
particular Django instance, but one of the most important settings is
ROOT_URLCONF. The ROOT_ URLCONF setting tells Django which Python
module should be used as the URLconf for this Web site
 The view function is responsible for returning an HttpResponse object.

The typical flow—URLconf resolution to a view functions that returns an HttpResponse—


can be short-circuited or augmented via middleware.
 When an HTTP request comes in from the browser, a server-specific handler
constructs the HttpRequest passed to later components and handles the flow of the
response processing.

Navkis College of Engineering 9


FULL STAK DEVELOPMENT -21CS62

 The handler then calls any available Request or View middleware. These types of
middleware are useful for augmenting incoming HttpRequest objects as well as
providing special handling for specific types of requests.
 If either returns an HttpResponse, processing bypasses the view. Bugs slip by even the
best programmers, but exception middleware can help squash them.
 If a view function raises an exception, control passes to the exception middleware. If
this middleware does not return an HttpResponse, the exception is reraised. Even
then, all is not lost. Django includes default views that create a friendly 404 and 500
response.
 Finally, response middleware is good for postprocessing an HttpResponse just before
it’s sent to the browser or doing cleanup of request-specific resources.

URLconfs and Loose Coupling


In Django, URLconfs (short for URL configurations) and loose coupling go hand-in-hand as
a way to create modular and maintainable web applications. Here's how:
1.Loose Coupling Explained: Loose coupling is a software design principle that emphasizes
minimizing the interdependence between different parts of the code. This means changes
made in one section have minimal or no impact on other sections.
2. URLconfs and Loose Coupling in Action: Django's URLconfs are Python files (usually
named urls.py) that define how URLs map to view functions. This separation between URL
definitions and view implementations promotes loose coupling in several ways:
3.Independent URL Changes: Imagine you want to change the URL for a particular view
function (say, from /articles to /blog/articles). You can simply modify the URLconf without
touching the view function itself. This keeps the logic separate from the URL structure.
4. Independent View Function Changes: Let's say you need to modify the functionality
within a view function. You can update the code in the view function (usually in views.py)
without affecting the URL patterns. This allows you to evolve the view logic without
breaking the URL mapping.
5. URL Reuse: A single view function can be mapped to multiple URLs in the URLconf.
This promotes code reuse and reduces redundancy

Benefits of Loose Coupling with URLconfs:

Navkis College of Engineering 10


FULL STAK DEVELOPMENT -21CS62

• Maintainability: Independent changes to URLs and views make the code easier to
understand, modify, and debug.
• Flexibility: You can easily add new functionalities (views) and URLs without
affecting existing ones.
• Testability: Both URLs and views can be tested in isolation, simplifying the testing
process.

Errors in Django (404 Errors):


Django applications can encounter various errors during development and deployment. Here
are some common types of errors you might face:
Example:

To find out, try running the Django development server and hitting a page such as
http://127.0.0.1:8000/hello/ or http://127.0.0.1:8000/does-not-exist/, or even http://
127.0.0.1:8000/ (the site “root”). You should see a “Page not found” message Django displays
this message because you requested a URL that’s not defined in your URLconf.
Types of Errors:
1. Template Errors: These errors occur when Django encounters issues processing template
files. This could be due to syntax errors in your HTML templates, undefined template
variables, or problems with template tags.
2. View Errors: View errors happen when there's a problem with the Python code within
your view functions. This could include syntax errors, exceptions not handled properly, or
issues with the logic you've implemented.
3. URL Resolution Errors: These errors arise when Django cannot find a matching URL
pattern for a requested URL. This might be due to typos in your URL patterns, incorrect
regular expressions, or conflicts in how URLs are mapped.
4. Database Errors: If your Django application interacts with a database, you might
encounter errors related to database connections, queries, or data manipulation. These could
be due to incorrect database credentials, invalid SQL syntax, or problems with your database
schema.
5. Server Errors: These are more general errors that originate from the web server running
your Django application. Common causes include server misconfiguration, memory issues, or
permission problems.
• Here are some tips for debugging Django errors:

Navkis College of Engineering 11


FULL STAK DEVELOPMENT -21CS62

1. Consult Error Messages: Django error messages usually provide detailed


information about the nature of the error and the line of code where it occurred. Pay
close attention to the error traceback for clues.
2. Utilize Django Debug Mode: Django's debug mode provides extra debugging
information and aids in identifying errors during development.
3. Check Django Documentation: The Django documentation offers comprehensive
explanations and solutions for many common errors.
4. Use a Debugger: A Python debugger like PyCharm or pdb can help you step
through your code line by line and inspect variables to pinpoint the root cause of the
error.

Wildcard URLpatterns:
 Wildcard URL patterns in Django can be a powerful tool for handling a wide range of
URLs with a single definition. However, it's crucial to use them judiciously and
understand their potential drawbacks.
 How Wildcard Urlpatterns Work: Wildcard URL patterns are created using the re_path
function from django.urls and typically include the * notation. This notation matches
any number of characters in the URL path
Example: 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/
• 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),
Benefits of Wildcard URLpatterns:
1. Conciseness: They simplify URL definitions for handling many similar URLs.
2. Flexibility: A single pattern can accommodate various URL structures.

Navkis College of Engineering 12


FULL STAK DEVELOPMENT -21CS62

Drawbacks:
1. Reduced Readability: Wildcard patterns can make URLconfs less readable,
especially with complex regular expressions.
2. Overly Broad Matches: Uncarefully crafted patterns might unintentionally match
unintended URLs.
3. Reverse URL Challenges: Django's reverse function for generating URLs might not
work seamlessly because it requires knowing the exact captured wildcards during
URL generation.\
Multiple Specific Patterns: Define multiple specific URL patterns for better
maintainability.

Regular Expression

Navkis College of Engineering 13


FULL STAK DEVELOPMENT -21CS62

Navkis College of Engineering 14

You might also like