introduction to python and django

30
Introduction to (Python and) the Django Framework Prashant Punjabi Solution Street 9/26/2014

Upload: solutionstreet

Post on 25-Jun-2015

290 views

Category:

Technology


3 download

DESCRIPTION

Introduction to Python and Django

TRANSCRIPT

Page 1: Introduction to Python and Django

Introduction to (Python and)

the Django FrameworkPrashant Punjabi

Solution Street 9/26/2014

Page 2: Introduction to Python and Django

Python!

• Created by Guido van Rossum in the late 1980s !

• Named after ‘Monty Python’s Flying Circus’ !

• Python 2.0 was released on 16 October 2000 !

• Python 3.0 a major, backwards-incompatible release, was released on 3 December 2008 !

• Guido is the BDFL

Page 3: Introduction to Python and Django

Python• General Purpose, high-level programming language

• Supports multiple programming paradigms

• object-oriented, functional, structured, imperative(?)

• Dynamically typed

• Many implementations

• CPython (reference)

• Jython

• IronPython .. and many more

Page 4: Introduction to Python and Django

The Zen of Python• “Core philosophy”

• Beautiful is better than ugly

• Explicit is better than implicit

• Simple is better than complex

• Complex is better than complicated

• Readability counts

• >>> import this

Page 5: Introduction to Python and Django

Data Types• Numbers

• int, float, long (and complex)

• Strings

• str, unicode

• Sequence Types

• str, unicode, lists, tuples (and bytearrays, buffers, xrange)

• strings, tuples are ‘immutable’

• lists are mutable

• Mapping Types

• dict

Page 6: Introduction to Python and Django

Functions• Defined using the keyword.. def

• Followed by the function name and the parenthesized list of formal parameters.

• The statements that form the body of the function start at the next line,

• and must be indented (just like this line)

• The first statement of the function body can optionally be a string literal

• this string literal is the function’s documentation string, or docstring.

• Arguments are passed using call by value (where the value is always an object reference, not the value of the object)

• Functions always return a value

• If not return is explicitly defined, the function returns None

Page 7: Introduction to Python and Django

Control Flow• if

• if…elif…else

• for

• range

• break, continue, else

• while

Page 8: Introduction to Python and Django

Truthi-nessTM

• An empty list ([])

• An empty tuple (())

• An empty dictionary ({})

• An empty string ('')

• Zero (0)

• The special object None

• The object False (obviously)

• Custom objects that define their own Boolean context behavior (this is advanced Python usage)

Page 9: Introduction to Python and Django

Modules and Packages• A module is a file containing Python definitions and statements.

• The file name is the module name with the suffix .py appended.

• Within a module, the module’s name (as a string) is available as the value of the global variable __name__

• Modules can be executed as a script

• python module.py [args]

• __name__ is set to __main__

• Packages are a way of structuring Python’s module namespace by using “dotted module names”

• The __init__.py file is required to make Python treat a directory as containing packages

Page 10: Introduction to Python and Django

Classes• Python’s class mechanism adds classes with a minimum of new syntax and

semantics

• Python classes provide all the standard features of Object Oriented Programming

• multiple base classes

• a derived class can override any methods of its base class or classes

• a method can call the method of a base class with the same name

• Objects can contain arbitrary amounts and kinds of data

• Class and Instance Variables

• Static Methods

Page 11: Introduction to Python and Django

Standard Library• Operating System Interface

• File handling

• String pattern matching

• Regular expressions

• Mathematics

• Internet Access

• Dates and Times

• Collections

• Unit Tests

Page 12: Introduction to Python and Django

Batteries Included

Page 13: Introduction to Python and Django

Django

Page 14: Introduction to Python and Django

Django• Django grew organically from real-world applications

• Born in the fall of 2003, in Lawrence, Kansas, USA

• Adrian Holovaty and Simon Willison - web programmers at the Lawrence Journal-World newspaper

• Released it in July 2005 and named it Django, after the jazz guitarist Django Reinhard

• “For Perfectionists with Deadlines”

Page 15: Introduction to Python and Django

Getting Started• Installation

• pip install Django

• ¯\_(ツ)_/¯

• Creating a Django project

• django-admin.py startproject django_example

• Adding an ‘app’ to your Django project

• python manage.py startapp music

Page 16: Introduction to Python and Django

MVC - Separation of Concerns• models.py

• description of the database table, represented by a Python class, called a model

• create, retrieve, update and delete records in your database using simple Python code

• views.py

• contains the business logic for the page

• contains functions, each of which are called a view functions or simply views

• urls.py

• file specifies which view is called for a given URL pattern

• Templates

• describes the design of the page

• uses a template language with basic logic statements

Page 17: Introduction to Python and Django

models.py• Each model is represented by a class that subclasses django.db.models.Model

• Class variables represents a database fields in the model

• A field is represented by an instance of a Field class eg CharField, DateTimeField

• The name of each Field instance is used by the database as the column name

• Some Field classes have required arguments, others have optional arguments

• CharField, for example, requires that you give it a max_length

• default is an optional argument for many Field classes

• ForeignKey field is used to define relationships

• Django supports many-to-one, many-to-many and one-to-one

Page 18: Introduction to Python and Django

Queries• Each model has at least one Manager, and it’s called objects by default.

• Managers are accessible only via model classes

• Enforce a separation between “table-level” operations and “record-level” operations.

• A QuerySet represents a collection of objects from your database

• It can have zero, one or many filters

• A QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT.

• Example

Page 19: Introduction to Python and Django

Migrations• New in Django 1.7

• Previously accomplished by an external package called south

• Keeps the database in sync with the model objects

• Commands

• migrate

• makemigrations

• sqlmigrate

• squashmigrations

• Data Migrations

• python manage.py makemigrations --empty music

Page 20: Introduction to Python and Django

urls.py• Django lets you design URLs however you want, with no

framework limitations.

• “Cool URIs don’t change”

• URL configuration module (URLconf)

• simple mapping between URL patterns (regular expressions) to Python functions (views)

• capture parts of URL as parameters to view function (named groups)

• can be constructed dynamically

Page 21: Introduction to Python and Django

views.py• A Python function that takes a Web request and returns a Web response

• HTML contents of a Web page,

• a redirect, or a 404 error,

• an XML document,

• an image

• . . . or anything

• The convention is to put views in a file called views.py

• but it can be pretty much anywhere on your python path

• ‘Django Shortcuts’

• redirect, reverse, render_to_response,

Page 22: Introduction to Python and Django

Templates• Designed to strike a balance between power and ease

• A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.).

• Variables - {{ variable }}

• Replaced with values when the template is evaluated

• Use a dot (.) to access attributes of a variable

• Dictionary lookup, attribute or method lookup or numeric index lookup

• {{ person.name }} or {{ person.get_full_name }} or {{ books.1 }}

• Filters can be used to modify variables for display

• {{ name|lower }}

Page 23: Introduction to Python and Django

Templates• Tags control the logic of the template

• {% tag %}

• Commonly used tags

• for

• if, elif and else

• block and extends - Template inheritance

Page 24: Introduction to Python and Django

Template Inheritance• Most powerful part of Django’s template engine

• Build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.

• {% extends %} must be the first template tag in that template.

• More {% block %} tags in your base templates are better

• Child templates don’t have to define all parent blocks\

Page 25: Introduction to Python and Django

Forms• Django handles three distinct parts of the work involved in forms

• preparing and restructuring data ready for rendering

• creating HTML forms for the data

• receiving and processing submitted forms and data from the client

• The Django Form class

• Form class’ fields map to HTML form <input> elements

• Fields manage form data and perform validation when a form is submitted

• Fields are represented to a user in the browser as HTML “widgets”

• Each field type has an appropriate default Widget class, but these can be overridden as required.

Page 26: Introduction to Python and Django

Batteries (still) included• Authentication and Authorization

• Emails

• File Uploads

• Session

• Caching

• Transactions

• .. and so on

Page 27: Introduction to Python and Django

See also..• The Django ‘admin’ app

• django-admin.py and manage.py

• ModelForms

• Generic Views or Class based views

• Static File deployment

• Settings

• Middleware

• Similar to Servlet Filters in Java

Page 28: Introduction to Python and Django

References• Python - Wikipedia page (http://en.wikipedia.org/wiki/

Python_(programming_language))

• The Python Tutorial (https://docs.python.org/2/tutorial/index.html)

• The Django Project (https://www.djangoproject.com/)

• The Django Book (http://www.djangobook.com/en/2.0/index.html)

• The Django Documentation (https://docs.djangoproject.com/en/1.7/)

Page 29: Introduction to Python and Django

Questions?

Page 30: Introduction to Python and Django

Thank you!