SlideShare une entreprise Scribd logo
1  sur  45
Télécharger pour lire hors ligne
An Introduction to Django Web
Framework
David Gibbons
September 2015
Joined Ammeon almost 2 years ago in Porcos team
Previously worked with Django web framework.... and liked it.
Fast development of new features, clean architecture, on top of a fast, stable, secure
framework.
Developed a Django-powered Web Application for energy management
Over 100 users logged in each week to view, analyse their data
Easy to manage user permissions for specific website features
About Me
2
Introduction
Getting Started
Architecture
Other Components
Demo
3
Agenda
Introduction
4
5
6
History
Created at Lawrence Journal-World
newspaper in 2003 in Kansas, USA
Adrian Holovaty and Simon Willison
initially wrote from scratch as nothing
fitted
Historically excellent documentation
Named after French Guitarist Django
Reinhardt
Open sourced in 2005
A high-level Python Web framework that encourages rapid development and clean,
pragmatic design
A free and open source web framework (public repository at https://github.
com/django/django)
Model–View–Controller (MVC) architectural pattern
Don’t Repeat Yourself (DRY) principle
Lots of out-of-the box features
What is Django?
7
8
Django Version History
What is a Web Framework?
9
Software framework designed to simplify your web development life
Handles many of the common operations associated with web development including:
● accessing the database
● creating HTML templates
● managing sessions
Promotes code reuse
Some other popular Python Web Frameworks
10
Flask: micro framework that provides a simple template for web development
Tornado: web framework and asynchronous networking library, noted for high
performance
Bottle: fast, simple lightweight micro web-framework
Pyramid: MVC framework with flexible component choices
CherryPy: mature object-oriented web framework - compact and simple
11
How popular is Django?
PyPI is the official 3rd party package repository for Python
Stats available on number of downloads in last week, month, year.
Django is the most downloaded web framework, is regularly updated by community
Websites using Django
12
Django and LITP
Plugin development similar to developing Django apps:
- Defined directory structure
- Makes use of classes and functions provided by a “core”
- Form validation in Django is similar to LITP plugin validation
- Models and migrations in Django similar to LITP APIs and migrations
13
Getting Started
14
Build a web application to allow the public to vote in polls, and view results
Typical requirement for a online news website (such a Lawrence Journal-World)
Three interested parties:
● A software developer creates the necessary models
● A site administrator creates/updates/deletes the polls
● A public website visitor votes in the polls and views results
Same example application as the official Django tutorial, for more detailed explanation
see https://docs.djangoproject.com/en/1.8/intro/tutorial01/
Polls Web Application
15
1. Django 1.8 needs at least Python 2.7 installed!
2. Create a new project directory, install Django (preferable with pip and virtualenv)
3. To create Django project “mysite” run:
Creates a directory structure which is the base of project:
16
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
$ django-admin.py startproject mysite
Django Quick Start Guide
4. Django supports 4 databases:
Update the settings.py file to use sqlite and ‘Europe/Dublin’.
5. To create the sqlite file and database tables initially needed by Django run:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
TIME_ZONE = 'Europe/Dublin'
17
$ python manage.py migrate
6. Run the built-in Django development server (default port 8000):
7. Open 127.0.0.1:8000 in web browser, and you should see a page saying “It worked!”
18
$ python manage.py runserver
8. A Django “project” is a collection of Django “app”s.
An app is an application that does something specific (blog or poll)
To start our new polls app, cd into ‘mysite’ and run:
This creates the directory structure for your ‘polls’ app:
19
$ django-admin.py startapp polls
polls/
__init__.py
admin.py
migrations/
__init__.py
models.py
tests.py
views.py
Application Quick Start Guide
9. Add polls application to INSTALLED_APPS in settings.py to activate ‘polls’ models
10. Start working on the models, views, urls and templates for the polls app!
20
INSTALLED_APPS = (
...
‘polls’
)
Django Architecture
21
What is MVC (Model-View-Controller)?
Software architectural pattern for user interfaces, popular in web applications.
Other MVC frameworks: Ruby-on-rails (Ruby), ASP.NET MVC (C# or Visual Basic)
Alternative Django-specific acronym is MTV (Model, Template, View) 22
Template - User facing
URLs - URL Configuration
View - Business Logic
Model - Database Table
23
Models
Single definitive source of information about data
Define the interface to the database, an auto-generated database API
Generally maps to a single database table, and each attribute represents a database
field
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
24
Once the models are defined, two commands are run to create the database tables:
Models (continued)
25
$ python manage.py makemigrations polls
$ python manage.py migrate polls
Views
Python function which takes a Web request, and returns a Web response
This response can be HTML for a web page, a redirect, a 404 Not Found error etc.
Contains the logic on what is returned from a particular request
Function-based or class-based
26
from django.http import HttpResponse
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ‘. ’.join([q.question_text for q in latest_question_list])
return HttpResponse(output)
Views (continued)
Often required to return some variables from the model to a HTML template. The
useful ‘render’ shortcut:
Views are also used to check that a user is logged in, and to handle HTTP GET and
POST requests (request.GET, request.POST)
27
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, ‘polls/index.html’, context)
URLs
Map a user request to the appropriate Django ‘view’
When accessed on the site, regex matching is performed on the path.
If no regex matched, then error handling is done.
Designed to make URLs elegant and understandable
A urls.py file for the base project and an urls.py file for each app.
28
URLs (continued)
<domain_name>/polls/ - directs the request to the views.index function
<domain_name>/polls/4/ - directs the request to the views.detail function with
argument 4
Optional “name” argument to reference a URL
29
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail')
]
Templates
Simply a text file. It can generate any-text based format (HTML, XML, CSV, etc.).
Site-wide templates live in a “templates” directory on the project base
App-specific templates live within the app ‘polls/templates’
Templates encourage separation of application and presentation logic (no Python
knowledge is required for templates)
Django has its own template engine and also supports Jinja2 engine
30
Templates (continued)
Contains variables “{{ }}”, which get replaced when the template is evaluated, and tags
“{% %}” which control the logic of the template
Template inheritance: A base HTML template can be used site-wide, and extended in
each template
31
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{
question.question_text }}</a></li>
{% endfor %}
</ul>
Other components
32
Admin
Useful auto-generated Django admin, which contains generated forms.
Should only be accessible by a trusted staff member to Create, Update, Delete site
content.
33
Admin (continued)
To use the admin, first create a superuser (with username and password):
Once done, login to the admin site at: “<domain_name>/admin/”
Use admin.py files in each app to decide what and how to display model content to the
staff user.
34
from django.contrib import admin
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fields = [‘pub_date’, ‘question_text’]
admin.site.register(Question, QuestionAdmin)
$ python manage.py createsuperuser
Static Files
Includes images, JavaScript and CSS
Create a new directory ‘static’ within your app for these files ‘polls/static’
If using static files outside of an app, set STATICFILES_DIR in the settings file
Use the ‘static’ template tag in templates to avoid hardcoding paths to static files:
35
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
Testing
“Code without tests is broken by design”
- Jacob Kaplan-Moss, one of original Django developers
To run the test cases for an app run:
By default test runner will find any file named “test*.py” in current working directory
To run tests requiring database access subclass “django.test.TestCase”, a subclass of
“unittest.TestCase” from the Python standard library
36
$ python manage.py test polls
Testing (continued)
A very useful Test client which acts as a dummy Web browser can:
● Simulate GET and POST request on a URL
● Check redirects are working
● Test that a given request is rendered by a certain template
37
from django.test import TestCase
class QuestionViewTest(TestCase):
def test_index_view_with_no_questions(self):
"""
If no questions exist, an appropriate message should be displayed
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
Demo
38
[david.gibbons@7V0DZY1 tech_talk]$ tree -I '*.pyc|*~' mysite/
mysite/
|-- db.sqlite3
|-- manage.py
|-- mysite
| |-- __init__.py
| |-- settings.py
| |-- urls.py
| `-- wsgi.py
|-- polls
| |-- admin.py
| |-- __init__.py
| |-- migrations
| | |-- 0001_initial.py
| | `-- __init__.py
| |-- models.py
| |-- static
| | `-- polls
| | |-- images
| | | `-- magic-pony-django-wallpaper.png
| | `-- style.css
| |-- templates
| | `-- polls
| | |-- detail.html
| | |-- index.html
| | `-- results.html
| |-- tests.py
| |-- urls.py
| `-- views.py
`-- templates
`-- admin
`-- base_site.html
39
40
3rd Party Packages
Often prefixed - “django-”:
- djangorestframework
- django-registration-redux
- django-admin-honeypot
- django-debug-toolbar
- django-storages
Many more can be searched for at www.djangopackages.com
41
More topics not touched on, including ...
Internationalisation and Localisation (translation)
Django shell
Caching frameworks
Django deployment
Django Middleware
42
Summary
Started at Lawrence Journal-World newspaper in Kansas, USA
Most downloaded Python web framework, powering many popular websites
in existence today
Architecture is based around models, views, URLs and templates
Other useful “out-of-the-box” components are the admin interface, static file
handling, testing and user management
Excellent documentation - learn by example
43
References and Useful Links
● https://docs.djangoproject.com/en/1.8/
● https://en.wikipedia.org/wiki/Django_(web_framework)
● https://wiki.python.org/moin/WebFrameworks
● http://twoscoopspress.org/
44
Thank you and volunteer for talks!
45

Contenu connexe

Tendances

JSF 2.0 (JavaEE Webinar)
JSF 2.0 (JavaEE Webinar)JSF 2.0 (JavaEE Webinar)
JSF 2.0 (JavaEE Webinar)
Roger Kitain
 
Flash Platformアップデート
Flash PlatformアップデートFlash Platformアップデート
Flash Platformアップデート
Mariko Nishimura
 

Tendances (20)

Oleh Zasadnyy "Progressive Web Apps: line between web and native apps become ...
Oleh Zasadnyy "Progressive Web Apps: line between web and native apps become ...Oleh Zasadnyy "Progressive Web Apps: line between web and native apps become ...
Oleh Zasadnyy "Progressive Web Apps: line between web and native apps become ...
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Angular js
Angular jsAngular js
Angular js
 
Java Web Programming on Google Cloud Platform [1/3] : Google App Engine
Java Web Programming on Google Cloud Platform [1/3] : Google App EngineJava Web Programming on Google Cloud Platform [1/3] : Google App Engine
Java Web Programming on Google Cloud Platform [1/3] : Google App Engine
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
 
Upload[1]
Upload[1]Upload[1]
Upload[1]
 
Vaadin & Web Components
Vaadin & Web ComponentsVaadin & Web Components
Vaadin & Web Components
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular U
 
Working with AngularJS
Working with AngularJSWorking with AngularJS
Working with AngularJS
 
The web - What it has, what it lacks and where it must go - Istanbul
The web - What it has, what it lacks and where it must go - IstanbulThe web - What it has, what it lacks and where it must go - Istanbul
The web - What it has, what it lacks and where it must go - Istanbul
 
How to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptHow to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScript
 
JSF 2.0 (JavaEE Webinar)
JSF 2.0 (JavaEE Webinar)JSF 2.0 (JavaEE Webinar)
JSF 2.0 (JavaEE Webinar)
 
Flash Platformアップデート
Flash PlatformアップデートFlash Platformアップデート
Flash Platformアップデート
 
Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend Developers
 
Using HttpWatch Plug-in with Selenium Automation in Java
Using HttpWatch Plug-in with Selenium Automation in JavaUsing HttpWatch Plug-in with Selenium Automation in Java
Using HttpWatch Plug-in with Selenium Automation in Java
 
Vaadin Components
Vaadin ComponentsVaadin Components
Vaadin Components
 
webcomponents (Jfokus 2015)
webcomponents (Jfokus 2015)webcomponents (Jfokus 2015)
webcomponents (Jfokus 2015)
 
Selenium Automation in Java Using HttpWatch Plug-in
 Selenium Automation in Java Using HttpWatch Plug-in  Selenium Automation in Java Using HttpWatch Plug-in
Selenium Automation in Java Using HttpWatch Plug-in
 
Web Components for Java Developers
Web Components for Java DevelopersWeb Components for Java Developers
Web Components for Java Developers
 

Similaire à An Introduction to Django Web Framework

django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
Kevin Wu
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Ilian Iliev
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
Ganga Ram
 

Similaire à An Introduction to Django Web Framework (20)

بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
 
Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)
 
Company Visitor Management System Report.docx
Company Visitor Management System Report.docxCompany Visitor Management System Report.docx
Company Visitor Management System Report.docx
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django
DjangoDjango
Django
 
Why Django for Web Development
Why Django for Web DevelopmentWhy Django for Web Development
Why Django for Web Development
 
Django by rj
Django by rjDjango by rj
Django by rj
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem v
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Django framework
Django framework Django framework
Django framework
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
 
Django introduction
Django introductionDjango introduction
Django introduction
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
 
Django
DjangoDjango
Django
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

An Introduction to Django Web Framework

  • 1. An Introduction to Django Web Framework David Gibbons September 2015
  • 2. Joined Ammeon almost 2 years ago in Porcos team Previously worked with Django web framework.... and liked it. Fast development of new features, clean architecture, on top of a fast, stable, secure framework. Developed a Django-powered Web Application for energy management Over 100 users logged in each week to view, analyse their data Easy to manage user permissions for specific website features About Me 2
  • 5. 5
  • 6. 6 History Created at Lawrence Journal-World newspaper in 2003 in Kansas, USA Adrian Holovaty and Simon Willison initially wrote from scratch as nothing fitted Historically excellent documentation Named after French Guitarist Django Reinhardt Open sourced in 2005
  • 7. A high-level Python Web framework that encourages rapid development and clean, pragmatic design A free and open source web framework (public repository at https://github. com/django/django) Model–View–Controller (MVC) architectural pattern Don’t Repeat Yourself (DRY) principle Lots of out-of-the box features What is Django? 7
  • 9. What is a Web Framework? 9 Software framework designed to simplify your web development life Handles many of the common operations associated with web development including: ● accessing the database ● creating HTML templates ● managing sessions Promotes code reuse
  • 10. Some other popular Python Web Frameworks 10 Flask: micro framework that provides a simple template for web development Tornado: web framework and asynchronous networking library, noted for high performance Bottle: fast, simple lightweight micro web-framework Pyramid: MVC framework with flexible component choices CherryPy: mature object-oriented web framework - compact and simple
  • 11. 11 How popular is Django? PyPI is the official 3rd party package repository for Python Stats available on number of downloads in last week, month, year. Django is the most downloaded web framework, is regularly updated by community
  • 13. Django and LITP Plugin development similar to developing Django apps: - Defined directory structure - Makes use of classes and functions provided by a “core” - Form validation in Django is similar to LITP plugin validation - Models and migrations in Django similar to LITP APIs and migrations 13
  • 15. Build a web application to allow the public to vote in polls, and view results Typical requirement for a online news website (such a Lawrence Journal-World) Three interested parties: ● A software developer creates the necessary models ● A site administrator creates/updates/deletes the polls ● A public website visitor votes in the polls and views results Same example application as the official Django tutorial, for more detailed explanation see https://docs.djangoproject.com/en/1.8/intro/tutorial01/ Polls Web Application 15
  • 16. 1. Django 1.8 needs at least Python 2.7 installed! 2. Create a new project directory, install Django (preferable with pip and virtualenv) 3. To create Django project “mysite” run: Creates a directory structure which is the base of project: 16 mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py $ django-admin.py startproject mysite Django Quick Start Guide
  • 17. 4. Django supports 4 databases: Update the settings.py file to use sqlite and ‘Europe/Dublin’. 5. To create the sqlite file and database tables initially needed by Django run: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } TIME_ZONE = 'Europe/Dublin' 17 $ python manage.py migrate
  • 18. 6. Run the built-in Django development server (default port 8000): 7. Open 127.0.0.1:8000 in web browser, and you should see a page saying “It worked!” 18 $ python manage.py runserver
  • 19. 8. A Django “project” is a collection of Django “app”s. An app is an application that does something specific (blog or poll) To start our new polls app, cd into ‘mysite’ and run: This creates the directory structure for your ‘polls’ app: 19 $ django-admin.py startapp polls polls/ __init__.py admin.py migrations/ __init__.py models.py tests.py views.py Application Quick Start Guide
  • 20. 9. Add polls application to INSTALLED_APPS in settings.py to activate ‘polls’ models 10. Start working on the models, views, urls and templates for the polls app! 20 INSTALLED_APPS = ( ... ‘polls’ )
  • 22. What is MVC (Model-View-Controller)? Software architectural pattern for user interfaces, popular in web applications. Other MVC frameworks: Ruby-on-rails (Ruby), ASP.NET MVC (C# or Visual Basic) Alternative Django-specific acronym is MTV (Model, Template, View) 22
  • 23. Template - User facing URLs - URL Configuration View - Business Logic Model - Database Table 23
  • 24. Models Single definitive source of information about data Define the interface to the database, an auto-generated database API Generally maps to a single database table, and each attribute represents a database field from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') 24
  • 25. Once the models are defined, two commands are run to create the database tables: Models (continued) 25 $ python manage.py makemigrations polls $ python manage.py migrate polls
  • 26. Views Python function which takes a Web request, and returns a Web response This response can be HTML for a web page, a redirect, a 404 Not Found error etc. Contains the logic on what is returned from a particular request Function-based or class-based 26 from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ‘. ’.join([q.question_text for q in latest_question_list]) return HttpResponse(output)
  • 27. Views (continued) Often required to return some variables from the model to a HTML template. The useful ‘render’ shortcut: Views are also used to check that a user is logged in, and to handle HTTP GET and POST requests (request.GET, request.POST) 27 from django.shortcuts import render from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, ‘polls/index.html’, context)
  • 28. URLs Map a user request to the appropriate Django ‘view’ When accessed on the site, regex matching is performed on the path. If no regex matched, then error handling is done. Designed to make URLs elegant and understandable A urls.py file for the base project and an urls.py file for each app. 28
  • 29. URLs (continued) <domain_name>/polls/ - directs the request to the views.index function <domain_name>/polls/4/ - directs the request to the views.detail function with argument 4 Optional “name” argument to reference a URL 29 from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail') ]
  • 30. Templates Simply a text file. It can generate any-text based format (HTML, XML, CSV, etc.). Site-wide templates live in a “templates” directory on the project base App-specific templates live within the app ‘polls/templates’ Templates encourage separation of application and presentation logic (no Python knowledge is required for templates) Django has its own template engine and also supports Jinja2 engine 30
  • 31. Templates (continued) Contains variables “{{ }}”, which get replaced when the template is evaluated, and tags “{% %}” which control the logic of the template Template inheritance: A base HTML template can be used site-wide, and extended in each template 31 <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul>
  • 33. Admin Useful auto-generated Django admin, which contains generated forms. Should only be accessible by a trusted staff member to Create, Update, Delete site content. 33
  • 34. Admin (continued) To use the admin, first create a superuser (with username and password): Once done, login to the admin site at: “<domain_name>/admin/” Use admin.py files in each app to decide what and how to display model content to the staff user. 34 from django.contrib import admin from .models import Question class QuestionAdmin(admin.ModelAdmin): fields = [‘pub_date’, ‘question_text’] admin.site.register(Question, QuestionAdmin) $ python manage.py createsuperuser
  • 35. Static Files Includes images, JavaScript and CSS Create a new directory ‘static’ within your app for these files ‘polls/static’ If using static files outside of an app, set STATICFILES_DIR in the settings file Use the ‘static’ template tag in templates to avoid hardcoding paths to static files: 35 {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
  • 36. Testing “Code without tests is broken by design” - Jacob Kaplan-Moss, one of original Django developers To run the test cases for an app run: By default test runner will find any file named “test*.py” in current working directory To run tests requiring database access subclass “django.test.TestCase”, a subclass of “unittest.TestCase” from the Python standard library 36 $ python manage.py test polls
  • 37. Testing (continued) A very useful Test client which acts as a dummy Web browser can: ● Simulate GET and POST request on a URL ● Check redirects are working ● Test that a given request is rendered by a certain template 37 from django.test import TestCase class QuestionViewTest(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.")
  • 39. [david.gibbons@7V0DZY1 tech_talk]$ tree -I '*.pyc|*~' mysite/ mysite/ |-- db.sqlite3 |-- manage.py |-- mysite | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py |-- polls | |-- admin.py | |-- __init__.py | |-- migrations | | |-- 0001_initial.py | | `-- __init__.py | |-- models.py | |-- static | | `-- polls | | |-- images | | | `-- magic-pony-django-wallpaper.png | | `-- style.css | |-- templates | | `-- polls | | |-- detail.html | | |-- index.html | | `-- results.html | |-- tests.py | |-- urls.py | `-- views.py `-- templates `-- admin `-- base_site.html 39
  • 40. 40
  • 41. 3rd Party Packages Often prefixed - “django-”: - djangorestframework - django-registration-redux - django-admin-honeypot - django-debug-toolbar - django-storages Many more can be searched for at www.djangopackages.com 41
  • 42. More topics not touched on, including ... Internationalisation and Localisation (translation) Django shell Caching frameworks Django deployment Django Middleware 42
  • 43. Summary Started at Lawrence Journal-World newspaper in Kansas, USA Most downloaded Python web framework, powering many popular websites in existence today Architecture is based around models, views, URLs and templates Other useful “out-of-the-box” components are the admin interface, static file handling, testing and user management Excellent documentation - learn by example 43
  • 44. References and Useful Links ● https://docs.djangoproject.com/en/1.8/ ● https://en.wikipedia.org/wiki/Django_(web_framework) ● https://wiki.python.org/moin/WebFrameworks ● http://twoscoopspress.org/ 44
  • 45. Thank you and volunteer for talks! 45