0% found this document useful (0 votes)
10 views12 pages

Mod 1

The document provides an overview of web frameworks, specifically focusing on Django, which simplifies web application development by handling repetitive tasks. It explains the MVC (Model-View-Controller) design pattern, detailing how Django structures applications to separate concerns, making them easier to maintain and scale. Additionally, it covers Django's history, the process of creating views and URL configurations, and the importance of loose coupling in Django applications.

Uploaded by

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

Mod 1

The document provides an overview of web frameworks, specifically focusing on Django, which simplifies web application development by handling repetitive tasks. It explains the MVC (Model-View-Controller) design pattern, detailing how Django structures applications to separate concerns, making them easier to maintain and scale. Additionally, it covers Django's history, the process of creating views and URL configurations, and the importance of loose coupling in Django applications.

Uploaded by

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

MOD 1

1. WEB FRAMEWORK

It is a software framework that provides the necessary tools, libraries, and conventions to
simplify the development of web applications. It typically includes pre-built components for
handling common tasks such as routing, user authentication, database interactions, form
handling, and session management.

In the context of Python, Django is a popular web framework that aims to streamline web
development by providing an infrastructure for building web applications quickly and efficiently.
It handles many of the repetitive tasks that a developer would otherwise have to code manually,
such as setting up database connections, managing requests and responses, and rendering HTML
templates.

The example you've provided, a simple Python CGI script that displays the ten most recently
published books from a database, highlights some of the challenges and limitations of writing
web applications from scratch:

1. Boilerplate Code: The developer has to manually include certain lines of code (such as
printing the "Content-Type" line) and ensure tasks like closing the database connection
are handled properly. A web framework eliminates this repetitive code by providing
built-in functions and structures to handle these tasks automatically.
2. Code Reusability: If multiple parts of the application need to connect to the database,
this code would need to be duplicated across several scripts. A web framework allows for
the centralization of such logic, making the application more modular and easier to
maintain.
3. Environment-Specific Configuration: Managing different environments (such as
development, testing, and production) and database configurations can be cumbersome
with standalone scripts. A web framework often includes configuration management
features that allow the application to adapt to different environments more easily.
4. Separation of Logic and Presentation: In the example, the business logic (retrieving
book titles from the database) and the presentation (generating HTML) are tightly
coupled, making it difficult for non-developers (like web designers) to work on the
HTML without potentially breaking the Python code. A web framework, like Django,
promotes the separation of concerns, where business logic and presentation are separated
into different layers, allowing designers to work on HTML templates without affecting
the underlying code.
2. MVC (Model-View-Controller)
The MVC (Model-View-Controller) design pattern is a way of structuring web applications to
separate the concerns of handling data, user interactions, and the user interface. This separation
makes it easier to maintain and scale the application because each component has a distinct role,
and changes to one component are less likely to impact others.

Breakdown of the Django Example Using MVC

In the Django example provided:

1. Model (models.py):
o The Model represents the data structure and the logic for interacting with the
database.
o The Book class in models.py defines the structure of the Book table in the
database, including fields like name (the title of the book) and pub_date (the
publication date).
o Django automatically creates the SQL for interacting with the database (CRUD
operations) based on this Python class.

python
Copy code
from django.db import models

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

2. View (views.py):
o The View handles the business logic and the response to user requests.
o The latest_books function in views.py queries the Book model to get the latest
10 books from the database and then returns the data to be rendered in an HTML
template.
o The view is responsible for processing the user request, fetching the data, and
rendering the appropriate response.

python
Copy code
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})
3. Controller (urls.py):
o The Controller manages the flow of the application. It maps URLs to views,
determining which view function should handle a particular URL.
o In urls.py, the patterns function links the URL /latest/ to the
latest_books view function.

python
Copy code
from django.conf.urls.defaults import *
import views

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

4. View (Template: latest_books.html):


o The View (in MVC), in the context of Django, also refers to the Template, which
controls how the data is displayed to the user.
o In latest_books.html, we define the structure of the HTML page. The template
uses the Django template language to insert the book_list data dynamically and
generate the HTML content.

html
Copy code
<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
<ul>
{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
</body></html>

Advantages of MVC:

1. Separation of Concerns: Each component (Model, View, Controller) has a distinct


responsibility. This makes the codebase easier to manage and more modular. For
instance:
o Developers can modify the business logic in the model without affecting the user
interface.
o Web designers can modify the HTML template without worrying about the
underlying data or logic.
o The database schema can be changed independently of how the application
handles requests.
2. Loose Coupling: The components in an MVC design are loosely coupled, meaning
changes to one component don't require changes in others. For example, changing the
database schema (model) might only require changes in the model and views, without
touching the controller or template.
3. Scalability and Maintainability: Since components are separate, it’s easier to extend
and maintain the application as it grows. You can easily add new features, modify
existing ones, or swap out individual components (e.g., switching to a different database)
without breaking the entire application.

In Summary:

 Model: Represents the data structure and logic (interacts with the database).
 View: Contains the business logic and renders the final output (combines data and
templates).
 Controller: Manages the request-response flow, mapping URLs to views.

3. Django’s History:
Django's history highlights how it was developed out of necessity by real-world web developers
facing time constraints and demanding deadlines. Here's a brief overview of Django's journey:

Origins of Django:

 The Initial Problem: Adrian Holovaty and Simon Willison, web developers for the
Lawrence Journal-World newspaper, found themselves repeatedly building similar web
applications for various local news websites. Over time, they realized they were
reinventing the wheel for each project.
 Development of a Solution: To save time and improve efficiency, they started creating a
framework that would allow them to reuse code across different projects. This framework
became essential for meeting tight deadlines, as features and applications needed to be
built quickly and with minimal effort.

Django's Formalization:

 Summer 2005: After refining their internal framework, the team, now including Jacob
Kaplan-Moss, decided to release it as open-source software. They named it "Django"
after the jazz guitarist Django Reinhardt, as a nod to their love for jazz music.

Django's Culture:

 Real-World, Practical Focus: Django was built by developers who were working under
real-world conditions and facing deadlines in a fast-paced environment. As such, Django
is deeply focused on solving practical web development challenges, especially those
encountered in newsrooms and fast-moving industries.
 Open-Source Community: Since its release, Django has evolved with contributions
from a wide open-source community, with updates and improvements occurring
regularly. The developers, motivated by their own need for efficiency, prioritize features
that save time, ensure maintainability, and perform well under high traffic.

Key Lessons from Django’s History:

 Solving Real Problems: Django's design and features were driven by real-world
requirements rather than theoretical exercises, ensuring it was practical and easy to use
for developers.
 Rapid Development: Django was created to enable rapid development of maintainable
web applications, making it especially useful for teams with tight deadlines.
 Community-Driven: The open-source nature of Django means that it's actively
improved by developers who use it in their own projects, ensuring it continues to meet
the evolving needs of web developers.

4. Your First Django View and URLconf


Let's break down the steps for creating your first view and connecting it to a URL in Django.

Creating a View

In Django, a view is simply a Python function that takes a web request as input and returns a web
response. Here's how you define a simple view:

1. Create a views.py file: Inside your project directory (e.g., mysite), create a file named
views.py to hold your view functions.
o Example:

from django.http import HttpResponse

def hello(request):
return HttpResponse("Hello world")

2. Explanation:
o Import HttpResponse: You import HttpResponse from django.http because
it's used to return the HTTP response.
o Define the hello function: This function takes request (an instance of
HttpRequest) as its parameter. Even though you're not using request in this
example, it's a requirement for all views.
o Return an HttpResponse: The function returns HttpResponse("Hello
world"), which will display the text "Hello world" when accessed via a URL.
Connecting the View to a URL

To make Django recognize this view and show it when a specific URL is requested, you need to
map the URL to the view function using a URLconf (URL configuration).

1. Update urls.py:
o Open or create the urls.py file in your project (inside the mysite directory).
o The urlpatterns list tells Django which view function to call for each URL
pattern.

Example of URLconf:

from django.conf.urls import patterns


from mysite.views import hello

urlpatterns = patterns('',
(r'^hello/$', hello),
)

2. Explanation:
o Import the hello view: This makes the hello function available in the
URLconf.
o Add URL pattern: The tuple ('^hello/$', hello) maps the URL /hello/ to
the hello view. Here's how:
 ^ means the pattern must match the beginning of the string (the start of the
URL).
 $ means the pattern must match the end of the string (the end of the URL).
 So, the URL pattern ^hello/$ will only match exactly /hello/ and not
anything else like /hello/world/.

Testing the View

To see the view in action:

1. Run the Django development server:


python manage.py runserver

2. Access the URL in your browser: Open a browser and go to


http://127.0.0.1:8000/hello/. You should see the text "Hello world" displayed on
the page, which confirms that your view is properly hooked to the URL.
Key Concepts
 Views: Functions that take a request and return a response. They process requests and
send back responses, usually HTML, JSON, or other types of data.
 URLconf: A mapping between URLs and views, telling Django which view should
handle a particular request.
 Regular Expressions in URL Patterns: Django uses regular expressions to match
URLs, which allows for powerful and flexible URL routing.
5. SHOWS THE CURRENT DATE AND TIME.

1. Update views.py

To create the current_datetime view, you need to:

 Import the datetime module to get the current date and time.
 Define a new view function, current_datetime, which will return the current date and
time formatted in an HTML response.

Here’s how the updated views.py would look:

python
Copy code
from django.http import HttpResponse
import datetime

def hello(request):
return HttpResponse("Hello world")

def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)

2. Explanation of the Code:

 Import datetime: The datetime module is imported at the beginning to handle date and
time operations.
 current_datetime function: This function:
o Uses datetime.datetime.now() to get the current date and time.
o Formats the date and time into an HTML string using Python’s string formatting
(%s).
o Returns an HttpResponse that contains the HTML string.

3. Update urls.py

After defining the view in views.py, you need to link it to a URL in urls.py. This tells Django
which view function should be executed when a certain URL is requested.

Here’s the updated urls.py:

from django.conf.urls.defaults import *


from mysite.views import hello, current_datetime

urlpatterns = patterns('',
('^hello/$', hello),
('^time/$', current_datetime),
)
4. Explanation of urls.py:

 Import the views: The hello and current_datetime functions are imported from
views.py.
 URLpatterns: A URL pattern is added for /time/ that will invoke the
current_datetime view.

5. Testing the View

Now, you can test your view by running the development server:

1. Run the server: python manage.py runserver.


2. Visit http://127.0.0.1:8000/time/ in your browser.
3. You should see the current date and time displayed in your browser.

Output Example:

The output might look something like:

It is now 2025-01-11 14:25:15.394529.

6. Loose Coupling in Django


 Loose coupling is an important principle in Django where components (like URL
patterns and view functions) are independent of each other. This allows for changes to
one component without affecting the other. For example:
o If you want to change the URL (/time/) to something else, you can simply
modify the URLconf without altering the view logic.
o If you decide to modify the view function (e.g., changing how the date and time
are displayed), you don't need to change the URLconf.

This design encourages flexibility and makes maintaining your Django application easier.

Dynamic Time with URL Parameters

 The second concept focuses on creating a view that shows the current date and time with
a dynamic offset based on the URL.
o URL pattern: The r'^time/plus/(\d{1,2})/$' pattern captures an offset
(e.g., /time/plus/3/ would capture the number 3). This offset is passed to the
view function (hours_ahead).
o View function: The view function processes the offset and calculates the time
adjusted by the given number of hours. This is done using datetime.timedelta.

Regular Expressions in URLconf

 Django’s URLconf uses regular expressions to match patterns and pass data to views. In
this case, the URL /time/plus/(\d{1,2})/ captures a one- or two-digit number and
passes it to the view function as a parameter (offset).

The hours_ahead View Function

 The hours_ahead view takes the offset captured from the URL and:
1. Converts the string offset to an integer.
2. Adds that number of hours to the current date/time using datetime.timedelta.
3. Returns the updated time in an HTML response.

Here's a breakdown of the code:

python
Copy code
from django.http import Http404, HttpResponse
import datetime

def hours_ahead(request, offset):


try:
offset = int(offset) # Convert offset to an integer
except ValueError:
raise Http404() # If offset is not an integer, raise 404 error

# Calculate the current time + offset hours


dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
# Construct HTML response
html = "<html><body>In %s hour(s), it will be %s.</body></html>" %
(offset, dt)
return HttpResponse(html)

URLconf Example

The urls.py file needs to include this pattern for the view to work:

python
Copy code
from django.conf.urls import patterns
from mysite.views import hello, current_datetime, hours_ahead

urlpatterns = patterns('',
(r'^hello/$', hello),
(r'^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead), # Match and capture the offset
)

Handling Edge Cases

 The code includes error handling for invalid input, such as when the offset is not a valid
integer. Django raises a 404 error in such cases, ensuring robustness.
 The URL pattern restricts the valid input to one- or two-digit numbers, and it also ensures
that the URL does not accept an offset of more than 99 hours.

Testing the View

 With the development server running, visiting http://127.0.0.1:8000/time/plus/3/


will display the time 3 hours ahead.
 Trying out other URLs like http://127.0.0.1:8000/time/plus/100/ will result in a
404 error because the input exceeds the defined limit.

7. Django's error
It is page provides valuable information for debugging. When a Python error occurs, such as the
one introduced by commenting out the line offset = int(offset) in the hours_ahead view,
Django automatically presents a detailed error page with the following features:

1. Exception Information: At the top of the error page, Django shows the type of
exception (in this case, TypeError), along with the error message ("unsupported type for
timedelta hours component: unicode"). It also provides the filename and line number
where the error occurred.
2. Traceback: Django displays the full traceback, which includes all the function calls
leading to the error, along with the line numbers and the actual code at each step. This
can be very helpful for pinpointing the issue.
3. Source Code Context: You can click on any line of code in the traceback to view
surrounding lines of code. This allows you to understand the context in which the error
occurred.
4. Local Variables: By clicking "Local vars" under any traceback frame, you can inspect
the values of local variables at that point in the program. This helps to understand what
went wrong, especially if the error was caused by unexpected input or data.
5. Copy-and-Paste View: For easier sharing of error details, you can switch to a version of
the traceback that is easier to copy and paste. This is useful if you need to share the error
with colleagues or get help on forums or IRC channels.
6. Traceback Sharing: Django allows you to share the traceback by clicking the "Share
this traceback on a public Web site" button. This uploads the error details to dpaste.com,
generating a unique URL you can share with others.
7. Request Information: The error page also includes information about the HTTP request
that caused the error, including GET and POST parameters, cookies, and headers. This
can help you diagnose issues related to how data is sent to your application.
8. Settings: Django displays the settings for the current project, which can be useful if the
error is related to incorrect configuration.
9. Sensitive Information Warning: It's important to remember that this error page displays
sensitive information, such as the Python traceback and Django settings, which can be
exploited by attackers. For this reason, the Django error page should only be enabled in
debug mode. Once the application is ready for production, debug mode should be turned
off, which will prevent such error pages from being displayed.

8. In Django, wildcard URL


patterns allow you to capture dynamic parts of a URL using regular expressions. This is useful
when you need to match varying values in a URL, such as an offset in time or an ID number.

The example provided demonstrates how to use a wildcard URL pattern to match a URL with a
dynamic numerical value. Here's the breakdown:

Original Wildcard URLPattern


python
Copy code
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),
)

Explanation:

 The URL pattern r'^time/plus/\d+/$' matches URLs that include one or more digits
following /time/plus/.
o \d+ matches one or more digits, so URLs like /time/plus/2/, /time/plus/25/,
and /time/plus/100000000000/ would all be matched.
o The hours_ahead view will be called with the matched value as an argument.

Limiting the Range (1 to 99 Hours)

You can modify the regular expression to limit the range of accepted values for the offset to
between 1 and 99 hours by using the {1,2} quantifier:

python
Copy code
urlpatterns = patterns('',
(r'^time/$', current_datetime),
(r'^time/plus/\d{1,2}/$', hours_ahead),
)

Explanation of the Updated Pattern:

 \d{1,2} matches one or two digits, ensuring the offset is between 1 and 99 hours.
o For example, it would match /time/plus/2/ and /time/plus/25/ but not
/time/plus/100/ or /time/plus/1000/.
 This pattern ensures that only valid offsets of 1 to 99 hours are processed by the
hours_ahead view.

You might also like