web programming in django - emory university · web programming in django...

31
Web Programming in Django Introduction to its Model-View-Controller Architecture CS 370 SE Practicum, Cengiz Günay (Some slides courtesy of Eugene Agichtein and the Internets) Snowpacolypse ATL 2014 CS 370, Günay (Emory) Django MVC intro Spring 2014 1/5

Upload: phamdieu

Post on 11-Jul-2018

222 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Web Programming in DjangoIntroduction to its Model-View-Controller Architecture

CS 370 SE Practicum, Cengiz Günay

(Some slides courtesy of Eugene Agichtein and the Internets)

Snowpacolypse ATL 2014

CS 370, Günay (Emory) Django MVC intro Spring 2014 1 / 5

Page 2: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Agenda

Warm-up project:

Good proposals! ,Tentatively due Feb 13th

Today:

Intro to Django & its Model-View-Controller frameworkRunning Django on your laptops

Surveys first. . .

CS 370, Günay (Emory) Django MVC intro Spring 2014 2 / 5

Page 3: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Agenda

Warm-up project:

Good proposals! ,Tentatively due Feb 13th

Today:

Intro to Django & its Model-View-Controller frameworkRunning Django on your laptops

Surveys first. . .

CS 370, Günay (Emory) Django MVC intro Spring 2014 2 / 5

Page 4: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Agenda

Warm-up project:

Good proposals! ,Tentatively due Feb 13th

Today:

Intro to Django & its Model-View-Controller frameworkRunning Django on your laptops

Surveys first. . .

CS 370, Günay (Emory) Django MVC intro Spring 2014 2 / 5

Page 5: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Entry/Exit Surveys

Exit survey: Web ProgrammingTell me the steps between the server and client during an HTML webform display, submission, and response.To maintain user sessions, what pieces of persistent information mustbe stored on the client and the server side?

Entry survey: Django & MVCIn your opinion, what is the most useful feature of theModel-View-Controller approach?What parts of web programming are most tedious to you that youwould like it handled by a high-level web framework?

CS 370, Günay (Emory) Django MVC intro Spring 2014 3 / 5

Page 6: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of
Page 7: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

• high-level Python Web frameworkthat encourages rapid development and clean, pragmatic design.

• Django was designed to handle two challenges: – intensive deadlines

– stringent requirements of the experienced Web developers who wrote it.

• It lets you build high-performing, elegant Web applications quickly.

• Focuses on automating as much as possible

1/24/2013 CS 370, Spring 2012 18

Page 8: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Approach: Model-View-Controller

• Model: maintain state of application. Typically done with a database

• View: output to client, usually as HTML code, rendered by a web browser.

• Controller: interaction with user. handles user input, processes data and communicates with Model to save state.

1/29/2013 CS 370, Spring 2012 2

Formalized in 1979

Page 9: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

MVC

1/29/2013 CS 370, Spring 2012 3

Page 10: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Django flow

• 1) Visitor’s browser asks for a URL.2) Django matches the request against its urls.py files.3) If a match is found, Django moves on to the view that’s associated with the URL. Views are generally found inside each app in the views.py file.4) The view generally handles all the database manipulation. It grabs data and passes it on.5) A template (specified in the view) then displays that data.

1/29/2013 CS 370, Spring 2012 4

Page 11: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Site design in Django: review

• Goal: make common Web-development tasks fast

• Step 1: Design your model: model.py (M)

– Automatically create DB, APIs, admin interface

• Step 2: Design your views: views.py (V)

• Step 3: Design application logic: urls.py (C)

• Step 4: Design your templates:

• Step 5: Enjoy free bells & whistles (caching, syndication, …)

1/29/2013 CS 370, Spring 2012 5

Page 12: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Who cares?

• Spotify uses Django for some of their web sites. • Instagram uses Django for their web application [10]

• Yandex uses Django for their weather forecast site, OpenID provider, blog hosting service, internal Wiki and internal Mail Archives.

• Transifex – an open source platform for localization. • Bucketlist – uses Django to let users store life goals. • The Public Broadcasting Service• The Berkeley Graduate School of Journalism• Universal Subtitles uses Django for its free and open source collaborative

subtitling site. • FreeNAS uses Django for its web interface in its 8.0 major release.• PBS's Merlin, a platform for managing member stations' video metadata• Google internal stuff (details unknown).• ….

1/24/2013 CS 370, Spring 2012 20

Page 13: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Example Django Project

• Tutorial: https://docs.djangoproject.com/en/dev/intro/tutorial01/

– https://docs.djangoproject.com/en/dev/intro/tutorial03/

1/29/2013 CS 370, Spring 2012 6

Page 14: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Django Models

• A model is the single, definitive source of data about your data.

• Each model is a Python class that subclasses django.db.models.Model.

• Each attribute of the model represents a database field.

• Django gives you an automatically-generateddatabase-access API

1/29/2013 CS 370, Spring 2012 7

Page 15: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Example: Person (first_name, last_name)

• Define Person:from django.db import models

class Person(models.Model):

first_name = models.CharField(max_length=30)

last_name = models.CharField(max_length=30)

• What happens automaticallyCREATE TABLE myapp_person ( "id" serial NOT NULL

PRIMARY KEY, "first_name" varchar(30) NOT NULL,

"last_name" varchar(30) NOT NULL );

1/29/2013 CS 370, Spring 2012 8

Page 16: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Example: Person (first_name, last_name): 2

• Each field should be an instance of the Field class– The database column type (e.g. INTEGER, VARCHAR)

– The widget to use in Django's admin interface, if you care to use it (e.g. <input type="text">, <select>).

– The minimal validation requirements, used in Django'sautomatically-generated forms.

• Field reference:https://docs.djangoproject.com/en/1.3/ref/models/fields/#model-field-types

• More details: https://docs.djangoproject.com/en/1.3/topics/db/models/

1/29/2013 CS 370, Spring 2012 9

Page 17: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Django Models

• https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs

1/29/2013 CS 370, Spring 2012 10

Page 18: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Example 2: Django blog site

• Step-by-step tutorial: http://www.webmonkey.com/2010/02/get_started_with_django/

• Try using: http://dutch.mathcs.emory.edu:8100/blog/

• Admin interface: http://dutch.mathcs.emory.edu:8100/admin/

• Code: /home/cs370000/src/Django-1.3.1/blog/

• Start: python manage.py runserver 0.0.0.0:8100

1/29/2013 CS 370, Spring 2012 11

Page 19: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Recap: Django project pieces

• django-admin.py startproject blog

– blog/

__init__.py: A file required for Python to treat the mysitedirectory as a package

manage.py: A command-line utility that lets you interact with this project. Try: python manage.py help

settings.py: Settings/configuration for this project.

urls.py: The URLs for this project (“table of contents”)

1/29/2013 CS 370, Spring 2012 12

Page 20: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Django Project vs. App

1/29/2013 CS 370, Spring 2012 13

Page 21: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Django architecture encourages this

1/29/2013 CS 370, Spring 2012 14

Page 22: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Example:

1/29/2013 CS 370, Spring 2012 15

Page 23: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

URL dispatcher

• A clean, elegant URL scheme is an important detail in a high-quality Web application.

• Django lets you design URLs however you want

– There’s no .php or .cgi required

• Cool URIs don't change:

– http://www.w3.org/Provider/Style/URI

1/29/2013 CS 370, Spring 2012 16

Page 24: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

How Django processes a request

1. Determine the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, can be changed.

2. Load URLconf and looks for variable urlpatterns. This should be a Python list, in the format returned by the function django.conf.urls.patterns().

3. Iterate through each URL pattern, in order, and stop at the first one that matches the requested URL. (REGEX)

4. If one of the regexes matches, import and call the given view, which is a Python function. The view gets passed an HttpRequest as its first argument and any values captured in the regex as remaining arguments.

5. If no regex matches, or if an exception is raised during any point in this process, invoke an appropriate error-handling view.

1/29/2013 CS 370, Spring 2012 17

Page 25: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

2-minute REGEX review

1/29/2013 CS 370, Spring 2012 18

Symbol Matches

. (dot) Any single character

\d Any single digit

[A-Z] Any character between A and Z (uppercase)

[a-z] Any character between a and z (lowercase)

[A-Za-z] Any character between a and z (case-insensitive)

+ One or more of the previous expression (e.g., \d+ matches one or more digits)

[^/]+ One or more characters until (and not including) a forward slash

? Zero or one of the previous expression (e.g., \d? matches zero or one digits)

*Zero or more of the previous expression (e.g., \d* matches zero, one or more than one digit)

{1,3}Between one and three (inclusive) of the previous expression (e.g., \d{1,3} matches one, two or three digits)

http://www.djangoproject.com/r/python/re-module/

Page 26: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Python Regexes, cont’d

• To capture a value from the URL, just put parenthesis around it.

• There's no need to add a leading slash, because every URL has that.

• For example, it's ^wiki, not ^/wiki. The 'r' is optional but recommended.

• Named regular-expressions: (?P<name>pattern)

– (?P<page_name>[^/]+)/$',

1/29/2013 CS 370, Spring 2012 19

Page 27: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Example URLconf

from django.conf.urls.defaults import *

#http://cs370.mathcs.emory.edu:8100/wiki/CSRF

urlpatterns = patterns('',

(r'^wiki/(?P<page_name>[^/]+)/$',

'blog.wiki.views.view_page'),

(r'^wiki/(?P<page_name>[^/]+)/edit/$',

'blog.wiki.views.edit_page'),

(r'^wiki/(?P<page_name>[^/]+)/save/$',

'blog.wiki.views.save_page'),

)

1/29/2013 CS 370, Spring 2012 20

Page 28: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Passing Parameters to Views

CS 370, Günay (Emory) Django MVC intro Spring 2014 5 / 5

Page 29: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Good Design: Including other URLConfs

• Your urlpatterns can "include" other URLconfmodules.– Allows modular sites (good design)

• urlpatterns = patterns('',(r'^wiki/', include('blog.wiki.urls'))

)

– Note But: (wiki/urls.py):• (r'^(?P<page_name>[^/]+)/$', 'blog.wiki.views.view_page')

• More details:– https://docs.djangoproject.com/en/dev/topics/http/urls/

1/29/2013 CS 370, Spring 2012 21

Page 30: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Design Pattern: Include URLs

• There should be one urls.py at the project level, and one urls.py at each app level. The project level urls.py should include each of the urls.py under a prefix.:

• http://agiliq.com/books/djangodesignpatterns/urls.html

1/29/2013 CS 370, Spring 2012 22

Page 31: Web Programming in Django - Emory University · Web Programming in Django IntroductiontoitsModel-View-ControllerArchitecture CS370SEPracticum,CengizGünay (Some slides courtesy of

Onwards and upwords…

• Django book:

– http://www.djangobook.com/en/2.0/

• Common mistakes/gotchas:

– https://code.djangoproject.com/wiki/NewbieMistakes

• To be continued…

1/29/2013 CS 370, Spring 2012 29