Uploaded by Mr. Aryaman Sinha 4 Year B.Tech. Computer Science and Engineering

django lecture (3)

advertisement
Django
(A web development framework for Python)
By
Dr. Amrita Chaturvedi
Outline….
c
c
c
c
c
c
c
c
Introduction to Django
Django as MVC Design Pattern
DjangoArchitecture
Django Modules
Why Django for Web Development
Steps to create New Project
What Django generates
SampleApplication
Introduction – What is Django?
Django is pronounced JANG-oh. The “D” is silent.
c “Django is a high-level Python web framework that
encourages rapid development and clean, pragmatic
design.”
c The web framework for perfectionists with deadlines.
c Primary Focus
c
c
c
c
Dynamic and database driven websites
Content based websites
Example
c
c
Websites (Washingtonpost,eBay, craigslist)
Google AppEngine
Introduction…(Cont.)
c
History
c
c
c
c
Named after famous Guitarist “Django Reinhardt”
Developed by Adrian Holovaty and Jacob Kaplan-moss at
World Online News for efficient development
Open sourced in 2005
FirstVersion released September 3,2008
Introduction – Why Django?
1. Python
2. Batteries included
3. Doesn’t get in you way
4. Built – in admin
5. Scalable
6. Battle tested
7. Packages, packages and more packages!
8. Actively developed
9. Stable releases
10.First class documentation
1. Python
• Created in 1991 by Guido Van Rossum
• General Purpose Language
•
•
•
•
Clean Syntax
Easy to Learn
Easy to Debug
“Natural Feeling”
• Interpreted
•
•
•
No Compilation Phase
Multiplatform Integration
Native Debugger
• Duck Typing: As long as it quacks treat it like a duck
•
•
•
Override behaviors by creating methods
Implement operations by creating methods
All data is an object
Static Vs Dynamic Typing
•Typing refers to the data type in a programming language.
•Languages that have ‘static typing’ and ‘dynamic typing’ are said
to be ‘static typed’ and ‘dynamic typed’.
•Statically Typed Language:
•A language is statically typed if the type of a variable is
known at compile time.
•Every variable name is bound both to a type and to an
object.
•Once a variable name has been bound to a type (that is,
declared) it can be bound (via an assignment statement) only
to objects of that type
•Example: Java, C, C++
Static Vs Dynamic Typing
•Dynamically Typed Language:
•A language is dynamically typed if the type is associated
with run-time values, and not named variables/fields/etc.
•Every variable name is bound only to an object.
•Names are bound to objects at execution time by means of
assignment statements.
•It is possible to bind a name to objects of different types
during the execution of the program.
•Example: Perl, Ruby, Python.
Static Vs Dynamic Typing
Static Typing
String
employeeName
int employeeName
employeeName = 9
employeeName = "Steve Ferg"
Dynamic Typing
No error in dynamic
typing
Weak Vs Strong Typing
•In a weakly typed language (Example: Perl):
•variables can be implicitly coerced to unrelated types.
a=9
b = "9"
c = concatenate(a, b) // produces "99"
d = add(a, b) // produces 18
•In a strongly typed language (Example: Java, python):
•Implicit coercion of types is not allowed. Explicit conversion
is required.
•The last two statements would raise type exceptions.
•To avoid these exceptions, some kind of explicit type
conversion would be necessary:
a=9
b = "9"
c = concatenate( str(a), b)
d = add(a, int(b) )
Duck Typing
• An application of the duck test in type safety.
• Type checking is deferred to runtime.
• Implemented by means of dynamic typing.
• Establishes the suitability of an object for some purpose, using
the principle, "If it walks like a duck and it quacks like a duck,
then it must be a duck.“
• With normal typing, suitability is assumed to be determined by
an object's type only.
• In duck typing, an object's suitability is determined by the
presence of certain methods and properties (with appropriate
meaning), rather than the actual type of the object.
def test(o)
log o.getName # Let's hope this will work
end
2. Batteries Included
•Django inherits its “batteries included” philosophy from Python.
•Includes a lot of extra stuff you probably won’t need.
•Django implements some common, but complex processes by
providing simple tools and wrappers to hide the complexity
without compromising power.
•Django’s “batteries” are located in the contrib packages.
•Example:
•Admin — administration application
•Auth — authentication framework
•contenttypes—a framework for hooking into Django models
•gis—adds geospatial capabilities to Django
•sessions—a framework for managing anonymous sessions
3. Doesn't Get in your Way
•When you create a Django application:
•Django adds no unnecessary functions, no mandatory
imports, no third party libraries and no XML configuration
files.
•Django’s automatic tools (startproject and startapp) only
create a basic settings file, a few folders and some almost
empty starter files.
•It gives a solid foundation that you can build upon in any
way you like.
4. Built In Admin
•Provides an administration interface for working with
your models and managing users, user permissions and
groups.
•With model interface there is no need for a separate
database administration program.
•The admin also has an optional model documentation
feature that provides automatic documentation of your
models.
•Like the rest of Django, the admin is also customizable
and extendable.
5. Scalable
•Django is based on MVC architectural pattern
•Database, program code and display code are separate.
•Django takes this separation one step further by separating
code from the static media—images, files, CSS and JavaScript
•These design philosophies allow you to:
•Run separate servers for your database, applications and
media
•Easily have your media served from a Content Delivery
Network (CDN)
•Cache content at multiple levels and scopes
•For really big sites, employ clustering and load-balancing to
distribute your website across multiple servers.
6. Battle Tested
•After running for several years in the high demand
environment of a news organization, Django was open
sourced in 2005.
•After nearly 12 years of growth, Django now not only
runs news publishing companies like the Washington
Post, but is also running all or part of major global
enterprises like Pinterest, Instagram, Disqus, Bitbucket,
EventBrite and Zapier.
•Django continues to grow in popularity.
https://www.djangosites.org/ lists over 5200 sites
using Django, and that is only for sites that register with
Djangosites.
7. A Lot of Packages
•Many of Django’s large international community of developers
give back to the community by releasing their projects as opensource packages.
•Django Packages lists over 3400 reusable Django apps, sites and
tools to use in your own Django projects.
•A quick tour of popular packages includes:
•Cookiecutter—quick and easy setup of Django project and
app structures for more advanced applications
•Django ReST Framework—Implements a ReST API in Django
•Django allauth—Facebook, GitHub, Google and Twitter
authentication for your Django apps
•Debug toolbar—display debug information as your project is
running
•Django Celery—provides Celery integration for Django
•Oscar, Django Shop and Cartridge—eCommerce frameworks
for Django
8. Actively Developed
•One of the biggest risks of open source is whether
there is sufficient interest in the project for it to attract
developer support in the long term.
•There is no such risk with Django—it is supported by
an active community
•The Django development team maintains a
development roadmap on the Django Project
website (https://www.djangoproject.com/download/#s
upported-versions) and have a solid track record of
meeting roadmap milestones.
•The Django Project is also supported by an
independent foundation—the Django Software
Foundation—that is a registered non-profit in the US.
9. Stable Releases
•The downside of the ever-evolving development of an open-source software
project is the lack of a stable codebase on which to base commercial
development.
•Django addresses this issue with Long Term Support (LTS) versions of the
software and a defined release process.
•LTS versions are released with a guaranteed (typically three years) support
period. In this period the codebase is guaranteed to remain stable; with
patches for bugs, security and data loss 100% compatible with the feature
release.
•After a development phase, each release enters an Alpha phase where a
feature freeze is applied.
•The new release then moves through Beta and Release Candidate (RC) stages
where bugs are worked out of the release.
•If no major bugs are found for a period after the release candidate, the final
will be released (feature release).
•After the final has been released, only bugfixes and security patches are
applied.
10. First Class Documentation
•Django ensures that the documentation is comprehensive and
that the tutorials are easy to follow.
•Quality of the documentation can make one choose Django
over other options.
•Django also has strong support from community members who
produce free learning materials, books, paid and free courses
and lots of tips, tricks and assistance on their websites.
•Online learning material:
•Tango with Django: http://www.tangowithdjango.com/
•TwoScoops Press: https://www.twoscoopspress.com/
•Django Girls: https://djangogirls.org/
Django as an MVC Design Pattern
c
MVC Architecture:
c
Models
c
c
Views
c
c
Controls what a user sees
Templates
c
c
Describes your data structure/database schema
How a user sees it
Controller
c
c
The Django Framework
URL parsing
Django Modules
c
c
c
c
c
c
c
c
c
c
Administration interface (CRUD interface)
Authentication system
Comments system
Forms handling
Sessions
Syndication framework (RSS and Atom Feeds)
Caching
Internationalization
Localization
Custom Middleware
Django Architecture
Why Django for Web Development
c
Lets you divide code modules into logical groups to make it
flexible to change
c
c
c
c
Provides auto generated web admin to ease the website
administration
Provides pre-packaged API for common user tasks
Provides you template system to define HTML template for
your web pages to avoid code duplication
c
c
Loosely Coupled Principle
Allows you to separate business logic from the HTML
c
c
DRY Principle
Allows you to define what URL be for a given Function
c
c
MVC design pattern (MVT)
Separation of concerns
Everything is in python (schema/settings)
Django Models
•Provide an Object-relational Mapping (ORM) to the underlying database.
•Most common databases are programmed with some form of Structured Query
Language (SQL)
•An ORM tool provides a simple mapping between an object (the ‘O’ in ORM) and the
underlying database.
•Supported Databases: PostgreSQL, MySQL, SQLite, Oracle.
Django Templates
•A text file designed to separate an application’s data from the
way it is presented.
•Django templates are not limited to HTML—they can be used
for rendering several different text formats.
•The design of Django’s templates is based on three key
principles:
•A template system should separate program logic from
design.
•Templates should discourage redundancy—Don’t Repeat
Yourself (DRY).
•The template system should be safe and secure—code
execution in the template must be forbidden.
Separate Logic from Design
•Web design and web programming are two very different
disciplines.
•For all but the smallest projects, design and programming are
not done by the same people.
•Django’s template system enables the Django programmers and
website designers to work independently of each other.
<h1>Your Order Information</h1>
<p>Dear {{ person_name }},</p>
•The first couple of lines of an order confirmation page,
displayed on a website after the user has made a purchase.
•The majority of this code is plain HTML. The small bit of script in
bold is a Django variable tag.
•When this template is rendered in your browser, the template
will replace the variable person_name with the name passed to
the template by the view.
Don’t Repeat Yourself (DRY)
•The DRY principle is particularly evident in how Django uses template
inheritance.
•Template inheritance helps us to minimize repetition and redundant code.
•If you only wanted to create a few web pages, you could get away with
copying the front page and simply changing the content and saving each
different page as a HTML file.
•what if you needed to change the template?
Don’t Repeat Yourself (DRY)
•We fix this problem by creating a parent template that has the content that
is common to the entire website and then creating child templates that
inherit these common features and then adds any content unique to the child
template.
•Django supports multiple level of inheritance too. So there can be a child
template that adds only the side navigation to the parent, and then have a
third template that inherits from the child and adds the content.
Template Security
•Django’s solution to template security vulnerabilities is simple—
code execution is forbidden.
•Django’s template tags provide display logic only, this includes:
•Displaying variables—this can be simple text like a users
name, or more complex data like HTML formatted text.
•Choosing which content to display based on logical check(s),
e.g., if a user is logged in, then display user menu or useronly content.
•Iterating over lists of data—most often used to insert
database information into HTML lists.
•Formatting the data—for date formatting, text manipulation
and other filters that act on the data.
•Things that you can’t do in a Django template:
•Execute Python code
•Assign a value to a variable
•Perform advanced logic
Django Views
•Django’s views are the information brokers of a Django application. A view
sources data from your database (or an external data source or service) and
delivers it to a template.
•The view makes decisions on what data gets delivered to the template—
either by acting on input from the user, or in response to other business logic
and internal processes.
•Each Django view performs a specific function, and has an associated
template.
•Views are represented by either a Python function, or a method of a Python
class.
•To ease the burden on programmers, many common display tasks have builtin views in Django. There are four built-in function based views for displaying
error pages:
•The 404 (page not found) view
•The 500 (server error) view
•The 403 (HTTP Forbidden) view
•The 400 (bad request) view
URLconf – Tying it all Together
•we need to tell the view what to display in the browser, based on what the user has
requested.
•When a user clicks on a link on a website, a request for that URL is sent to Django.
•Once Django receives the requested URL, it must decide which view will deal with the
request.
•You, as the programmer, decide which view to serve at which URL by creating a URL
Configuration (URLconf for short) in a Python file named urls.py
•When Django finds a URL in urls.py that matches the requested URL, it calls the view
associated with that URL.
•The selected view then renders the content to a template, as per the business logic in
the view and sends the rendered content back to your browser for display.
Steps to create New Project
c
c
c
c
c
c
c
c
c
c
c
Create a project
Start an application
Create the database (MySQL, Postgresql, SQLite)
Define DB Settings in Settings.py
Define your models
Add pluggable modules
Write your templates
Define your views
Create URL mapping
Test Application
Deploy Application (Linux, Apache, mod_Python, DB)
What Django generates…
c
MySite/
c
c
c
c
c
init .py
Manage.py
// Script to interact with Django
Settings.py
// Config
URLs.py$ // My Site URL mapping
MyProject/
c
c
c
c
c
c
init .py
URLs.py
Models.py
Views.py
Admin.py
Templates
// Project specific URL mapping
// Data Models
// Contains the call back functions
Questions?
(Questions are guaranteed in life; Answers aren’t.)
c
c
c
c
For more information (Documentation,
Download and News)
c http://www.djangoproject.com/
A Good book to learn Django
c http://www.djangobook.com/en/1.0/
The best place to start
c http://docs.djangoproject.com/en/dev/
A lot of Django Pluggables available online
c Explore at
http://www.djangopluggables.com
Download