2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py...

42
S T-110.5130 Mobile Systems Programming Alberto Vila Tena alberto.vilatena(at)gmail(dot)com 28/01/2011

Upload: richard-webster

Post on 24-Dec-2015

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

S

T-110.5130 Mobile Systems ProgrammingAlberto Vila Tena

alberto.vilatena(at)gmail(dot)com28/01/2011

Page 2: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

2

What is Django?

What is Django? A Web Application Framework based in Python

And what is a Web Application Framework? An abstraction Provides generic functionality common to most web

applications Helps developers build web applications

Page 3: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

3

Model-View-Controller

An architectural pattern

Good for developing interactive applications

Page 4: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

4

Model-Template-View

Django’s approach to MVC

The model does the same as in MVC

The template determines how we see the data

The view determines which data we see

Routing configuration and the framework itself are responsible for choosing the right views

Page 5: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

5

Projects and apps

Project: Collection of configurations and apps for a particular web site

App: A web application with a concrete function

A project can contain many apps

An app can be part of multiple projects

Page 6: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

6

Creating a Django Project

Creates a directory mysite with the following structure

>> django-admin.py startproject mysite

/mysite__init__.py manage.pysettings.pyurls.py

Page 7: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

7

Utility Script «manage.py»

Creates the database schema of the project

Runs the project in the server

In the browser, localhost:«port number» shows your project

Other administrative tasks http://docs.djangoproject.com/en/dev/ref/django-admin/

>> python manage.py syncdb

>> python manage.py runserver «port number»

Page 8: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

8

Project Settings «settings.py»

Database settings

Template directories

Installed apps

Many other settings http://docs.djangoproject.com/en/dev/ref/settings/

You can also add your own settings

Page 9: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

9

Routing «urls.py»

The file urls.py maps URLs to the apps’ views

Mapping is done through pairs of A regular expression A view in a Django app

If an URL matches a regular expression➜ The related view gets called

Page 10: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

10

Routing Examples

from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('',

(r'^polls/$', 'polls.views.index'), (r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'), (r'^polls/(?P<poll_id>\d+)/results/$', 'polls.views.results'), (r'^polls/(?P<poll_id>\d+)/vote/$', 'polls.views.vote'), (r'^admin/', include(admin.site.urls)),

)

Page 11: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

11

Creating a Django App

Creates a directory myapp with the following structure

>> django-admin.py startapp myapp

/myapp__init__.py models.pytests.pyviews.py

Page 12: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

12

Django Models«models.py»

Describe the data layout of the application

Apply integrity checks

Use Object-Relational Mapping Simplifies the database definition Hides the database implementation

Page 13: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

13

Object-relational Mapping

Maps database tuples into objects Tables mapped into classes

Provides Data Consistency Database independence More variety and abstraction in data types

Page 14: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

14

Django Models (II)«models.py»

Defining a model class is like defining a normal class

Imports django.db.models module Defines special variable types

CharField, TextField, IntegerField, EmailField, DateTimeField… Defines relationships within models

ForeignKey, ManyToMany, OneToOne… Defines field options

Null, blank, unique, primary_key…

More info: http://docs.djangoproject.com/en/dev/topics/db/models/

Page 15: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

15

Django Models Example

from django.db import models class Poll(models.Model):

question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')

class Choice(models.Model):

poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField()

Page 16: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

16

Django Templates

Documents in a text format with python block tags {{ variable }} {{#comment#}} {{% code %}}

Templates separate presentation from content Minimizes coupling Changes in the presentation do not affect the content

Support HTML, XML, RSS…

Page 17: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

17

Django Template Language

Conditional sentences {% if condition %} … {% else %} … {% endif %}

Comparison {% ifequal a b %} … {% endifequal %}

Loops {% for a in b %} … {% endfor %}

More tags and filters http://docs.djangoproject.com/en/dev/ref/templates/bu

iltins/

Page 18: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

18

Template Inheritance

{% extends «template» %} Inherits the content of an already existing template

{% block «blockname» %} … {% endblock %} Defines code blocks in the parent template These blocks could be overwritten in the child

templates

Page 19: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

19

Django Views «views.py»

Receive and HttpRequest object

Define the business logic of the elements they show

Return an HttpResponse object

Page 20: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

20

HttpRequest

Gets created automatically when a view is requested

Contains metadata about the request, accessible through a set of variables GET, POST, COOKIES, session, FILES, encoding…

Object methods give information over the request is_ajax(), is_secure(), get_host()…

More information and full list of variables and methods: http://docs.djangoproject.com/en/dev/ref/request-response/

Page 21: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

21

HttpResponse

The user has to create it

Each view should return an HttpResponse object or raise an exception (HTTP 404, 500…)

There are subclasses for each HTTP status code HttpResponseRedirect (302), HttpResponseNotFound(404),

HttpResponseServerError(500)…

More information http://docs.djangoproject.com/en/dev/ref/request-response

/

Page 22: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

22

Rendering Templates from Views

1. Fetch a template

2. Wrap the data to be shown in a Context object

3. Render the template using the data

4. Return the rendered template as the HttpResponse

Page 23: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

23

Rendering Example

def example_view:template = get_template(”mytemplate.html”) #1data = Context({

’foo’: ’hello’, ’bar’: ’world’

}) #2output = template.render(data) #3return HttpResponse(output) #4

Page 24: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

24

Rendering shortcuts

HttpResponses are similar in most views We usually render a template, return an object or raise an

error

Shortcuts available in module django.shortcuts render_to_response redirect get_object_or_404, get_list_or_404

More info: http://docs.djangoproject.com/en/dev/topics/http/shortcuts/

Page 25: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

25

Useful Links

Django Tutorial http://docs.djangoproject.com/en/dev/intro/tutorial01

/

T-106.4300 Web Software Development slides More extended information about Django Basics of Python https://noppa.tkk.fi/noppa/kurssi/t-106.4300/etusivu

Django documentation http://docs.djangoproject.com/en/1.2/

Page 26: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

26

Useful Python Libraries

Encoding and decoding JSON simplejson (http://code.google.com/p/simplejson/)

Invoking REST APIs urllib (http://docs.python.org/library/urllib.html) urllib2 (http://docs.python.org/library/urllib2.html) httplib (http://docs.python.org/library/httplib.html)

Page 27: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

27

Python Tutorials

v. 2.7.1: http://docs.python.org/tutorial/

v. 2.5.2: http://docs.python.org/release/2.5.2/tut/tut.html

Page 28: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

28

References

Django documentation http://docs.djangoproject.com/en/1.2/

T-106.4300 Web Software Development slides Seppala & Karavirta, 2010 https://noppa.tkk.fi/noppa/kurssi/t-106.4300/etusivu

Page 29: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

SGoogle App Engine

Page 30: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

30

Installing Google App Engine

Download the SDK for Python from the following URL: http://code.google.com/appengine/downloads.html

Make sure a compatible Python installation (max 2.5.x) exists before starting to install the SDK

Register your Google account in Google App Engine and create an application

Page 31: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

31

Installing Google App Engine (II)

Page 32: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

32

First Execution of the Launcher

Page 33: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

33

The Django Helper for GAE

Download the Django Helper for GAE http://code.google.com/p/google-app-engine-django/

Decompress the file

Rename the decompressed directory with your project name

Open app.yaml and change the application field to your project

Application: mysite

Page 34: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

34

Supporting Django

Get a Django version http://www.djangoproject.com/download/

Decompress the file and copy the django folder into your project directory

Now you can create Django apps inside your project>> django-admin.py startapp myapp

Page 35: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

35

Defining Models

Standard Djangofrom django.db import models class Poll(models.Model):

question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')

class Choice(models.Model):

poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField()

Django in GAEfrom appengine_django.models import

BaseModelfrom google.appengine.ext import db

class Poll(BaseModel): question = db.StringProperty() pub_date =

db.DateTimeProperty('date published')

class Choice(BaseModel): poll = db.ReferenceProperty(Poll) choice = db.StringProperty() votes = db.IntegerProperty()

Page 36: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

36

Using Models with Google Datastore

New classes and commands for database queries Query GqlQuery

Wider variety of data types http://code.google.com/appengine/docs/python/datastore/type

sandpropertyclasses.html

It is not necessary to build tables explicitely Commands syncdb, validate and sql* for manage.py

become useless

More info: http://code.google.com/appengine/docs/python/datastore/

Page 37: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

37

Storing Static Content

Images, JavaScript files, CSS templates, etc get stored by default in a directory static inside your project directory

The directory static needs to be created

To change this default, change the following lines in app.yaml in the handlers section- url: /static static_dir: static

Page 38: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

38

Routing

Done also in the handlers section of app.yaml

By default it follows what you indicate in your urls.py

You can control other aspects about the URLs Secure access through HTTPS Authenticated access More info:

http://code.google.com/appengine/docs/python/config/appconfig.html

- url: /.* script: main.py

Page 39: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

39

Updated Django Settings

The helper changes some settings

DATABASE_ENGINE = 'appengine'DEBUG = TrueINSTALLED_APPS = ['appengine_django']MIDDLEWARE_CLASSES = ()ROOT_URLCONF = 'urls' ###SETTINGS_MODULE = 'mysite.settings' ###SITE_ID = 1 ###TEMPLATE_DEBUG = TrueTIME_ZONE = 'UTC'

Page 40: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

40

Importing the Project

In the Google App Engine Launcher File -> Add Existing Application Add your project directory

Page 41: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

41

References

Google App Engine documentation for Python http://code.google.com/appengine/docs/python/

Google App Engine Helper for Django documentation http://code.google.com/appengine/articles/appengin

e_helper_for_django.html

Page 42: 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py urls.py

S

Thank You!

42