. 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py...
-
Upload
richard-webster -
Category
Documents
-
view
221 -
download
0
Transcript of . 2 3 4 5 6 >> django-admin.py startproject mysite /mysite __init__.py manage.py settings.py...
S
T-110.5130 Mobile Systems ProgrammingAlberto Vila Tena
alberto.vilatena(at)gmail(dot)com28/01/2011
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
3
Model-View-Controller
An architectural pattern
Good for developing interactive applications
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
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
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
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»
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
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
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)),
)
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
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
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
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/
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()
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…
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/
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
19
Django Views «views.py»
Receive and HttpRequest object
Define the business logic of the elements they show
Return an HttpResponse object
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/
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
/
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
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
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/
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/
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)
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
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
SGoogle App Engine
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
31
Installing Google App Engine (II)
32
First Execution of the Launcher
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
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
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()
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/
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
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
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'
40
Importing the Project
In the Google App Engine Launcher File -> Add Existing Application Add your project directory
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
S
Thank You!
42