t-110.5130 mobile systems programming alberto vila tena alberto.vilatena (at) gmail ( dot ) com

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

Upload: minya

Post on 24-Feb-2016

34 views

Category:

Documents


0 download

DESCRIPTION

T-110.5130 Mobile Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com 28/01/2011 . What is Django?. What is Django? A Web Application Framework based in Python And what is a Web Application Framework? An abstraction - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

S

T-110.5130 Mobile Systems ProgrammingAlberto Vila Tena

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

Page 2: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

3

Model-View-Controller

An architectural pattern Good for developing interactive applications

Page 4: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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/bui

ltins/

Page 18: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

19

Django Views «views.py»

Receive and HttpRequest object Define the business logic of the elements they

show Return an HttpResponse object

Page 20: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

22

Rendering Templates from Views

1. Fetch a template2. Wrap the data to be shown in a Context object3. Render the template using the data4. Return the rendered template as the

HttpResponse

Page 23: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

SGoogle App Engine

Page 30: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

31

Installing Google App Engine (II)

Page 32: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

32

First Execution of the Launcher

Page 33: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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 projectApplication: mysite

Page 34: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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/typesa

ndpropertyclasses.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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

39

Updated Django Settings

The helper changes some settingsDATABASE_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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

40

Importing the Project

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

Page 41: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

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: T-110.5130 Mobile  Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

S

Thank You!

42