The Django web development framework for the Python-aware



Similar documents
django-gcm Documentation

Rapid Website Deployment With Django, Heroku & New Relic

depl Documentation Release depl contributors

Advanced Tornado TWENTYONE Advanced Tornado Accessing MySQL from Python LAB

latest Release 0.2.6

Using Python, Django and MySQL in a Database Course

Django Two-Factor Authentication Documentation

DEPLOYMENT GUIDE Version 1.1. Deploying F5 with IBM WebSphere 7

MyMoney Documentation

Installation & User Guide

Drupal CMS for marketing sites

Nupic Web Application development

Hypercosm. Studio.

Java Application Developer Certificate Program Competencies

DIPLOMA IN WEBDEVELOPMENT

PROJECT REPORT OF BUILDING COURSE MANAGEMENT SYSTEM BY DJANGO FRAMEWORK

Localizing dynamic websites created from open source content management systems

CSCI110 Exercise 4: Database - MySQL

Facebook Twitter YouTube Google Plus Website

Web Development with Flask and the Raspberry Pi Leading by Example CUAUHTEMOC CARBAJAL ITESM CEM 22/04/2014

Effective Django. Build Nathan Yergler

Certified PHP/MySQL Web Developer Course

CIS 192: Lecture 10 Web Development with Flask

EECS 398 Project 2: Classic Web Vulnerabilities

FileMaker Server 9. Custom Web Publishing with PHP

CS169.1x Lecture 5: SaaS Architecture and Introduction to Rails " Fall 2012"

Search help. More on Office.com: images templates

DEPLOYMENT GUIDE DEPLOYING F5 WITH MICROSOFT WINDOWS SERVER 2008

Applied Internet Technology (CSCI-UA.0480) - Sample Questions

1. To start Installation: To install the reporting tool, copy the entire contents of the zip file to a directory of your choice. Run the exe.

Kentico Site Delivery Checklist v1.1

<Insert Picture Here> Oracle Web Cache 11g Overview

DEPLOYMENT GUIDE Version 1.2. Deploying the BIG-IP system v10 with Microsoft Exchange Outlook Web Access 2007

Esigate Module Documentation

Copyright 2013 Consona Corporation. All rights reserved

Using SQL Server Management Studio

Gravity Forms: Creating a Form

Maximum Availability Architecture. Oracle Best Practices For High Availability

Errors That Can Occur When You re Running a Report From Tigerpaw s SQL-based System (Version 9 and Above) Modified 10/2/2008

Security Test s i t ng Eileen Donlon CMSC 737 Spring 2008

Skills for Employment Investment Project (SEIP)

web frameworks design comparison draft - please help me improve it focus on Model-View-Controller frameworks

Creating a Guest Book Using WebObjects Builder

LAMP [Linux. Apache. MySQL. PHP] Industrial Implementations Module Description

Qlik Sense Enabling the New Enterprise

Web Application Vulnerability Testing with Nessus

CMS Training. Prepared for the Nature Conservancy. March 2012

Kentico 8 Certified Developer Exam Preparation Guide. Kentico 8 Certified Developer Exam Preparation Guide

Django FTP Deploy Documentation

J j enterpririse. Oracle Application Express 3. Develop Native Oracle database-centric web applications quickly and easily with Oracle APEX

Web Application Frameworks. Robert M. Dondero, Ph.D. Princeton University

Introduction to web development with Python and Django Documentation

Site Configuration Mobile Entrée 4

DEPLOYMENT GUIDE Version 1.2. Deploying the BIG-IP System v10 with Microsoft IIS 7.0 and 7.5

INTRODUCING ORACLE APPLICATION EXPRESS. Keywords: database, Oracle, web application, forms, reports

Introduction to Django Web Framework

Response Time Analysis of Web Templates

How to start with 3DHOP

Java SE 8 Programming

Databases and Architecture of Wordpress MORTENESBENSEN

Table of Contents. Table of Contents

Integrating the F5 BigIP with Blackboard

Web Services for Management Perl Library VMware ESX Server 3.5, VMware ESX Server 3i version 3.5, and VMware VirtualCenter 2.5

10CS73:Web Programming

Introducing Apache Pivot. Greg Brown, Todd Volkert 6/10/2010

Vector HelpDesk - Administrator s Guide

Web Development Frameworks

Building native mobile apps for Digital Factory

A Tour of Silex and Symfony Components. Robert

Enterprise Service Bus

mkryptor allows you to easily send secure s. This document will give you a technical overview of how. mkryptor is a software product from

CommonSpot Content Server Version 6.2 Release Notes

Course Number: IAC-SOFT-WDAD Web Design and Application Development

USER GUIDE MANTRA WEB EXTRACTOR.

Commerce Services Documentation

Modern Web Application Framework Python, SQL Alchemy, Jinja2 & Flask

Web Framework Performance Examples from Django and Rails

Application Developer Guide

Student Employment Website User Guide for Off-Campus Employers

Django Assess Managed Nicely Documentation

Dell World Software User Forum 2013

DEPLOYMENT GUIDE DEPLOYING THE BIG-IP SYSTEM WITH MICROSOFT INTERNET INFORMATION SERVICES (IIS) 7.0

DEPLOYMENT GUIDE Version 1.2. Deploying F5 with Oracle E-Business Suite 12

End User Guide The guide for /ftp account owner

Serious Threat. Targets for Attack. Characterization of Attack. SQL Injection 4/9/2010 COMP On August 17, 2009, the United States Justice

A WEB INTERFACE FOR NATURAL LANGUAGE PROCESSING DRIVEN FAQ WEBSITE. A Thesis. Presented to the. Faculty of. San Diego State University

NASA Workflow Tool. User Guide. September 29, 2010

Exploratory Testing in an Agile Context

Web Apps: Using web apps to build amazing functionality without programming. I Love Web Apps. They re Awesome.

opalang - Rapid & Secure Web Development

SharePoint Integration Framework Developers Cookbook

How To Change Your Site On Drupal Cloud On A Pcode On A Microsoft Powerstone On A Macbook Or Ipad (For Free) On A Freebie (For A Free Download) On An Ipad Or Ipa (For

AWS Service Catalog. User Guide

LAMBDA CONSULTING GROUP Legendary Academy of Management & Business Development Advisories

Slides from INF3331 lectures - web programming in Python

Online shopping store

An Newsletter Using ASP Smart Mailer and Advanced HTML Editor

Creating Online Surveys with Qualtrics Survey Tool

How to test and debug an ASP.NET application

Transcription:

The Django web development framework for the Python-aware Bill Freeman PySIG NH September 23, 2010 Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 1 / 18 Introduction Django is a web development framework. While most parts are optional, this means that it: Accepts requests (typically HTTP GET and POST) Garners information from URLs Interacts with a database (CRUD) Composes a response (templates, Python) Does session management Helps with pesky details, e.g.; CSRF Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 2 / 18

Incoming Front-end Server Django s native client-facing interface is WSGI (Web Services Gateway Interface). Django includes a development server that is convenient for, well, development, connecting HTTP to WSGI (with a few extras). In deployment, however, one should use a server like Apache or NGiNX to meet the TCP/IP interface, do SSL, and to serve truly static files such as CSS, JS, images, PDFs, etc. Now that mod python is dead, mod wsgi is pretty much the universal answer for connecting the front-end server and Django. There are WSGI interfaces for other front ends, or connectors that hide WSGI under the hood. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 3 / 18 Request Path Parsing Incoming Django parses the request URL s path using a urlconf. A urlconf has a list (or equivalent) of urlpattern objects. It applies each urlpattern in turn to the path the urlconf was given against, stopping when one succeeds, returning its result. (If no urlpattern succeeds, the urlconf fails, see below.) A urlpattern has a regular expression (regex). If a the regex of a urlpattern doesn t match the path string, the urlpattern fails. If the regex matches then: If the urlpattern has a view function then the urlpattern succeeds, returning the view function and maybe other stuff. Otherwise the urlpattern has a sub-urlconf. The urlpattern removes the portion of the path that it matched and applies its urlconf to the remainder. The urlpattern succeeds if its urlconf does. If the top level urlconf fails, Django returns a 404 response (page not found). Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 4 / 18

Incoming Gathering View Function Arguments A urlpattern s regex may include groups which are used as arguments to the view function. Unnamed groups are used as positional arguments: r digest/month/(20\d\d)-(\d\d?)/ would match digest/month/2010-9/ and would collect 2010, and 9 as positional arguments. Named groups are used as keyword arguments: r digest/month/(?p<year>20\d\d)-(?p<month>\d\d?)/ would match the same string, but pass 2010 as the year argument, and 9 as month. Each urlpattern may also have a dictionary of extra keyword arguments. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 5 / 18 View functions Presentation A view function is an ordinary Python function. An HttpRequest object is always passed as the first positional argument. The function may accept additional arguments. Any that are not optional must be supplied by means of the urlpatterns involved in choosing the view function. The HttpRequest object has, among other things: A method attribute, identifying the kind of HTTP request being processed. A GET attribute, a mapping of query parameter names to values. A POST attribute, a mapping of POST parameter names to values. A view function typically returns an HttpResponse object. It will be returned to the front end for transmission to the client. HttpRedirect objects are another possibility. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 6 / 18

Presentation Templates, variable references, context variables Django templates are mostly HTML. Special constructs begin with {{, {% or {#, and end, respectively, with }}, %} or #} (variable references, tags, and comments). The beginning and ending sequences must be on the same line. Variable reference inserts something into the document: {{ foo }} Inserts unicode() of the value of the foo context variable. Most context variables are provided by the code that wants the template rendered. The variable can be de-referenced using dot: {{ foo.bar }} Gets the bar attribute of foo, calling if it is a method, or gets foo[ bar ] if foo is a mapping. If foo were a list, foo.1 would get its second element. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 7 / 18 Templates filters Variables can be filter ed: {{ foo.bar upper }} Presentation Makes the result upper case. You can use multiple filters in a pipeline. Some filters can take an argument: {{ foo.start date date: D d M Y }} Foo s attribute, presumably a date or datetime, is formatted as you like. Normally variable references are escaped to prevent inadvertent insertion of HTML markup from the variable value: {{ foo.bar upper safe }} Some filters mark their result to avoid the escaping. safe is one such, and that is its only purpose. You can write your own filters in Python. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 8 / 18

Presentation Templates tags Tags MAY provide text output: {% now D d M Y %} Shows today s date. Tags MAY be paired with a closing tag: {% for f in foo.fields %}{{ f.name }}: {{ f.value }}<br/>{% endfor %} Iterates foo.fields, as you might expect. Any previous value of the context variable f is restored after the endfor. You can access the loop counter in various ways using the forloop context variable. The boolean forloop.last, plus the if tag, could be used to eliminate the <br/> HTML tag the last time through. Tags can take a variable number of arguments. You can write your own tags in Python. It is, however, harder than writing filters. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 9 / 18 Presentation Templates using other templates The include tag does what it sounds like, inserting the rendered output of another template into the including template. (This actually is much less used that the extends tag, see below.) The extends tag and block tag implement template inheritance. The extends tag must be first in a template, and can occur only once. The base template (the one mentioned in the extends tag) is rendered instead of the derived template (the one using extends). A base template can also use the extends tag, to any depth. The block tag takes a name argument, and, with the endblock tag, defines a named block. The content of a named block in a derived template replaces the content of any block with the same name in its chain of bases. base templates can provide site-wide common features. Templates a level up can provide section specific differences. Top level templates implement the final page type details. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 10 / 18

Presentation Form support Django aids in the production of HTML forms. You create a python sub-class of Django Form class. Most class attributes are instances of Django form.field classes. A class instance can render itself as INPUT and SELECT tags. Make the instance a template context variable, say form. The template says, for example, (within a FORM tag): {{ form.as p }} A dictionary of initial field values can be provided at instantiation. When the form is submitted, the view function passes request.post (or request.get) to a new instantiation of the class, and then says: if(form.is valid()): Each Field knows how to validate the submitted data. If a field is invalid, and the form instance is rendered again, an error string is shown near the INPUT. A valid form provides a dictionary of submitted values for the view function to use. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 11 / 18 Models Object Relational Mapper Model classes correspond to database tables. Model class instances correspond to database rows. Many model class attributes correspond to database columns. Corresponding model class instance attributes hold python objects representing database values. Model Field attributes, along with the Django database back end code, know how to convert between the python representation of values and the SQL representation of those values. Model Fields validate instance values before saving an instance to the database, when the save method of the Model instance is called. Model Fields include support for foreign key (many to one) and many to many relationships (the m2m join tables are handled by Django). Model Forms are Forms that use Model classes to define the form s fields, can be initialized from a Model instance, and know how to transfer form field data to Model instance fields. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 12 / 18

Object Relational Mapper Querysets A queryset remembers selection criteria for a given Model. No database query is made until a queryset is evaluated. A common evaluation is to iterate over a queryset which generates a series of Model instances. A queryset can be refined, which really returns a new queryset with both the original queryset s selection criteria, and the refinements. Selection criteria are specified using keyword arguments to the queryset methods filter, exclude, or get. The name of the keyword argument provides the name of the field to be tested, and, optionally, what kind of test (if other than equality) to make against the value of the keyword argument. ModelName.objects.filter(end date gte=datetime.datetime.now()) Selects rows, which, according to their end date column, have already ended. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 13 / 18 Admin Things you don t have to write for yourself. django.contrib.admin is a plug-able app : Easy to generate a section of an admin interface from a model. Can create, delete, edit and search model instances/table rows without writing your own urlpattern, view function, forms, and templates. Easy to customize what is shown, what is editable, how it is grouped, and what is searchable. There are many other plug-able apps, including CMS, blog, wiki, tagging, UI enhancing, etc. Some, like admin, are bundled with Django, but nearly all are available using pip or easy install. You may still want to customize one, or write your own to get exactly the performance you want: this is Open Source, so have at it. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 14 / 18

Odds and ends Middleware Settings specifies a stack (sequence, really) of middleware classes. The classes, in order, get a crack at the request before url parsing. They can modify the request object, gather information, return a response, including a redirect, or do nothing if this request isn t interesting. The classes get a second crack after url parsing, but before the view function is called. (There is middleware, for example, that checks whether the view function has the attribute applied by the login required decorator.) When a view function returns a response, the middleware, in reverse order (popping the stack?) gets a crack at the response, before it is returned to the front end, on the way to the client. If, instead, the view function raises an exception, the middleware gets, in reverse order, a crack at the exception. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 15 / 18 Odds and ends Template Context Processors A view function may choose to pass a request context to provide the values of template variables for a template rendering. RequestContext, which creates a request context object, is passed the request object, plus any explicit context variable definitions the view function wishes to provide. The RequestContext constructor offers the request object to each template context processor listed in settings.py. Any of the template context processors can return a dictionary of additional context variable definitions. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 16 / 18

Odds and ends Not covered Template search path. Writing your own template tags and filters. Additional manage.py commands. Writing additional manage.py commands. Multiple databases. Non-SQL databases. Using legacy databases. Shortcuts. Generic views. Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 17 / 18 More information Further reading http://docs.djangoproject.com/ http://groups.google.com/group/django-users http://pypi.python.org/pypi/virtualenv http://www.python.org/dev/peps/pep-0370/ And, of course, http://python.org/ Bill Freeman (PySIG NH) Introduction to Django September 23, 2010 18 / 18