FullStack-MODULE1
FullStack-MODULE1
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
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
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.
Example that demonstrates the difference between the previous approach and that undertaken
using a Web framework
Django is a free and open source web application framework which offers fast and effective
dynamic website development.
urlpatterns = patterns('',
(r'latest/$', views.latest_books),
)
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.
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
# (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:
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.
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:
(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
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 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.
• 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.
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:
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.
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