T110 5130 Mobile Systems Programming Alberto Vila Tena
T-110. 5130 Mobile Systems Programming Alberto Vila Tena alberto. vilatena(at)gmail(dot)com 28/01/2011 S
What is Django? S A Web Application Framework based in Python S And what is a Web Application Framework? S An abstraction S Provides generic functionality common to most web applications S Helps developers build web applications 2
Model-View-Controller S An architectural pattern S Good for developing interactive applications 3
Model-Template-View S Django’s approach to MVC S The model does the same as in MVC S The template determines how we see the data S The view determines which data we see S Routing configuration and the framework itself are responsible for choosing the right views 4
Projects and apps S Project: Collection of configurations and apps for a particular web site S App: A web application with a concrete function S A project can contain many apps S An app can be part of multiple projects 5
Creating a Django Project >> django-admin. py startproject mysite S Creates a directory mysite with the following structure /mysite __init__. py manage. py settings. py urls. py 6
Utility Script «manage. py» S Creates the database schema of the project >> python manage. py syncdb S Runs the project in the server >> python manage. py runserver «port number» S In the browser, localhost: «port number» shows your project S Other administrative tasks S http: //docs. djangoproject. com/en/dev/ref/django-admin/ 7
Project Settings «settings. py» S Database settings S Template directories S Installed apps S Many other settings S http: //docs. djangoproject. com/en/dev/ref/settings/ S You can also add your own settings 8
Routing «urls. py» S The file urls. py maps URLs to the apps’ views S Mapping is done through pairs of S A regular expression S A view in a Django app S If an URL matches a regular expression ➜ The related view gets called 9
Routing Examples from django. conf. urls. defaults import * from django. contrib import 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)), ) 10
Creating a Django App >> django-admin. py startapp myapp S Creates a directory myapp with the following structure /myapp __init__. py models. py tests. py views. py 11
Django Models «models. py» S Describe the data layout of the application S Apply integrity checks S Use Object-Relational Mapping S Simplifies the database definition S Hides the database implementation 12
Object-relational Mapping S Maps database tuples into objects S Tables mapped into classes S Provides S Data Consistency S Database independence S More variety and abstraction in data types 13
Django Models (II) «models. py» S Defining a model class is like defining a normal class S Imports django. db. models module S Defines special variable types S Char. Field, Text. Field, Integer. Field, Email. Field, Date. Time. Field… S Defines relationships within models S Foreign. Key, Many. To. Many, One. To. One… S Defines field options S Null, blank, unique, primary_key… S More info: S http: //docs. djangoproject. com/en/dev/topics/db/models/ 14
Django Models Example from django. db import models class Poll(models. Model): question = models. Char. Field(max_length=200) pub_date = models. Date. Time. Field('date published') class Choice(models. Model): poll = models. Foreign. Key(Poll) choice = models. Char. Field(max_length=200) votes = models. Integer. Field() 15
Django Templates S Documents in a text format with python block tags S {{ variable }} S {{#comment#}} S {{% code %}} S Templates separate presentation from content S Minimizes coupling S Changes in the presentation do not affect the content S Support HTML, XML, RSS… 16
Django Template Language S Conditional sentences S {% if condition %} … {% else %} … {% endif %} S Comparison S {% ifequal a b %} … {% endifequal %} S Loops S {% for a in b %} … {% endfor %} S More tags and filters S http: //docs. djangoproject. com/en/dev/ref/templates/builtins/ 17
Template Inheritance S {% extends «template» %} S Inherits the content of an already existing template S {% block «blockname» %} … {% endblock %} S Defines code blocks in the parent template S These blocks could be overwritten in the child templates 18
Django Views «views. py» S Receive and Http. Request object S Define the business logic of the elements they show S Return an Http. Response object 19
Http. Request S Gets created automatically when a view is requested S Contains metadata about the request, accessible through a set of variables S GET, POST, COOKIES, session, FILES, encoding… S Object methods give information over the request S is_ajax(), is_secure(), get_host()… S More information and full list of variables and methods: S http: //docs. djangoproject. com/en/dev/ref/request-response/ 20
Http. Response S The user has to create it S Each view should return an Http. Response object or raise an exception (HTTP 404, 500…) S There are subclasses for each HTTP status code S Http. Response. Redirect (302), Http. Response. Not. Found(404), Http. Response. Server. Error(500)… S More information S http: //docs. djangoproject. com/en/dev/ref/request-response/ 21
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 Http. Response 22
Rendering Example def example_view: template = get_template(”mytemplate. html”) #1 data = Context({ ’foo’: ’hello’, ’bar’: ’world’ }) #2 output = template. render(data) #3 return Http. Response(output) #4 23
Rendering shortcuts S Http. Responses are similar in most views S We usually render a template, return an object or raise an error S Shortcuts available in module django. shortcuts S render_to_response S redirect S get_object_or_404, get_list_or_404 S More info: S http: //docs. djangoproject. com/en/dev/topics/http/shortcuts/ 24
Useful Links S Django Tutorial S http: //docs. djangoproject. com/en/dev/intro/tutorial 01/ S T-106. 4300 Web Software Development slides S More extended information about Django S Basics of Python S https: //noppa. tkk. fi/noppa/kurssi/t-106. 4300/etusivu S Django documentation S http: //docs. djangoproject. com/en/1. 2/ 25
Useful Python Libraries S Encoding and decoding JSON S simplejson (http: //code. google. com/p/simplejson/) S Invoking REST APIs S urllib (http: //docs. python. org/library/urllib. html) S urllib 2 (http: //docs. python. org/library/urllib 2. html) S httplib (http: //docs. python. org/library/httplib. html) 26
Python Tutorials S v. 2. 7. 1: http: //docs. python. org/tutorial/ S v. 2. 5. 2: http: //docs. python. org/release/2. 5. 2/tut. html 27
References S Django documentation S http: //docs. djangoproject. com/en/1. 2/ S T-106. 4300 Web Software Development slides S Seppala & Karavirta, 2010 S https: //noppa. tkk. fi/noppa/kurssi/t-106. 4300/etusivu 28
Google App Engine S
Installing Google App Engine S Download the SDK for Python from the following URL: S http: //code. google. com/appengine/downloads. html S Make sure a compatible Python installation (max 2. 5. x) exists before starting to install the SDK S Register your Google account in Google App Engine and create an application 30
Installing Google App Engine (II) 31
First Execution of the Launcher 32
The Django Helper for GAE S Download the Django Helper for GAE S http: //code. google. com/p/google-app-engine-django/ S Decompress the file S Rename the decompressed directory with your project name S Open app. yaml and change the application field to your project Application: mysite 33
Supporting Django S Get a Django version S http: //www. djangoproject. com/download/ S Decompress the file and copy the django folder into your project directory S Now you can create Django apps inside your project >> django-admin. py startapp myapp 34
Defining Models Standard Django in GAE from django. db import models from appengine_django. models import Base. Model from google. appengine. ext import db class Poll(models. Model): question = models. Char. Field(max_length=200) pub_date = models. Date. Time. Field('date published') class Poll(Base. Model): question = db. String. Property() pub_date = db. Date. Time. Property('date published') class Choice(models. Model): poll = models. Foreign. Key(Poll) choice = models. Char. Field(max_length=200) votes = models. Integer. Field() class Choice(Base. Model): poll = db. Reference. Property(Poll) choice = db. String. Property() votes = db. Integer. Property() 35
Using Models with Google Datastore S New classes and commands for database queries S Query S Gql. Query S Wider variety of data types S http: //code. google. com/appengine/docs/python/datastore/typ esandpropertyclasses. html S It is not necessary to build tables explicitely S Commands syncdb, validate and sql* for manage. py become useless S More info: S http: //code. google. com/appengine/docs/python/datastore/ 36
Storing Static Content S Images, Java. Script files, CSS templates, etc get stored by default in a directory static inside your project directory S The directory static needs to be created S To change this default, change the following lines in app. yaml in the handlers section - url: /static_dir: static 37
Routing S Done also in the handlers section of app. yaml S By default it follows what you indicate in your urls. py - url: /. * script: main. py S You can control other aspects about the URLs S Secure access through HTTPS S Authenticated access S More info: http: //code. google. com/appengine/docs/python/config/appconfig. htm l 38
Updated Django Settings S The helper changes some settings DATABASE_ENGINE = 'appengine' DEBUG = True INSTALLED_APPS = ['appengine_django'] MIDDLEWARE_CLASSES = () ROOT_URLCONF = 'urls' ### SETTINGS_MODULE = 'mysite. settings' ### SITE_ID = 1 ### TEMPLATE_DEBUG = True TIME_ZONE = 'UTC' 39
Importing the Project S In the Google App Engine Launcher S File -> Add Existing Application S Add your project directory 40
References S Google App Engine documentation for Python S http: //code. google. com/appengine/docs/python/ S Google App Engine Helper for Django documentation S http: //code. google. com/appengine/articles/appengine_help er_for_django. html 41
Thank You! 42 S
- Slides: 42