450 likes | 629 Views
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
E N D
T-110.5130 Mobile SystemsProgramming Alberto Vila Tena alberto.vilatena(at)gmail(dot)com 28/01/2011
Whatis Django? • Whatis Django? • A Web Application Framework based in Python • And whatis a Web Application Framework? • Anabstraction • Providesgenericfunctionalitycommontomost web applications • Helpsdevelopersbuild web applications
Model-View-Controller • An architectural pattern • Good for developing interactive applications
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
Projectsandapps • Project: Collection ofconfigurationsandappsfor a particular website • App: A webapplicationwith a concrete function • A project can containmanyapps • Anapp can be partofmultipleprojects
Creating a Django Project • Creates a directorymysitewiththefollowingstructure >> django-admin.pystartprojectmysite /mysite __init__.py manage.py settings.py urls.py
Utility Script «manage.py» • Creates the databaseschema of the project • Runs the project in the server • In the browser, localhost:«portnumber» showsyourproject • Otheradministrativetasks • http://docs.djangoproject.com/en/dev/ref/django-admin/ >> python manage.py syncdb >> python manage.py runserver«portnumber»
Project Settings «settings.py» • Databasesettings • Templatedirectories • Installedapps • Manyothersettings • http://docs.djangoproject.com/en/dev/ref/settings/ • You can alsoaddyourownsettings
Routing«urls.py» • The file urls.pymapsURLstotheapps’ views • Mappingis done throughpairsof • A regular expression • A view in a Djangoapp • Ifan URL matches a regular expression • Therelatedviewgetscalled
RoutingExamples fromdjango.conf.urls.defaults import * fromdjango.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)), )
Creating a DjangoApp • Creates a directorymyappwiththefollowingstructure >> django-admin.py startappmyapp /myapp __init__.py models.py tests.py views.py
Django Models«models.py» • Describe the data layout of theapplication • Applyintegritychecks • Use Object-RelationalMapping • Simplifiesthedatabasedefinition • Hidesthedatabaseimplementation
Object-relationalMapping • Mapsdatabasetuples into objects • Tablesmapped into classes • Provides • Data Consistency • Databaseindependence • Morevariety and abstraction in data types
Django Models (II)«models.py» • Defining a modelclass is likedefining a normalclass • Importsdjango.db.modelsmodule • Definesspecialvariabletypes • CharField, TextField, IntegerField, EmailField, DateTimeField… • Definesrelationshipswithinmodels • ForeignKey, ManyToMany, OneToOne… • Definesfieldoptions • Null, blank, unique, primary_key… • More info: • http://docs.djangoproject.com/en/dev/topics/db/models/
DjangoModelsExample fromdjango.db import models classPoll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('datepublished') classChoice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField()
DjangoTemplates • Documents in a textformatwithpython block tags • {{ variable }} • {{#comment#}} • {{% code %}} • Templatesseparatepresentationfromcontent • Minimizescoupling • Changes in thepresentation do notaffectthecontent • Support HTML, XML, RSS…
DjangoTemplateLanguage • Conditionalsentences • {% ifcondition %} … {% else %} … {% endif %} • Comparison • {% ifequal a b %} … {% endifequal %} • Loops • {% for a in b %} … {% endfor %} • Moretags and filters • http://docs.djangoproject.com/en/dev/ref/templates/builtins/
TemplateInheritance • {% extends «template» %} • Inherits the content of an alreadyexistingtemplate • {% block «blockname» %} … {% endblock %} • Definescodeblocks in the parenttemplate • Theseblockscouldbeoverwritten in the childtemplates
Django Views«views.py» • Receive and HttpRequestobject • Define thebusinesslogic of theelementsthey show • ReturnanHttpResponseobject
HttpRequest • Getscreatedautomaticallywhen a view is requested • Contains metadata about the request, accessiblethrough a set of variables • GET, POST, COOKIES, session, FILES, encoding… • Objectmethodsgiveinformationover the request • is_ajax(), is_secure(), get_host()… • Moreinformation and fulllist of variables and methods: • http://docs.djangoproject.com/en/dev/ref/request-response/
HttpResponse • The userhas to createit • Eachviewshouldreturn an HttpResponseobjectorraise an exception (HTTP 404, 500…) • Therearesubclasses for each HTTP status code • HttpResponseRedirect (302), HttpResponseNotFound(404), HttpResponseServerError(500)… • Moreinformation • http://docs.djangoproject.com/en/dev/ref/request-response/
RenderingTemplatesfromViews • Fetch a template • Wrap the data to beshown in a Contextobject • Render the templateusing the data • Return the renderedtemplate as the HttpResponse
RenderingExample defexample_view: template = get_template(”mytemplate.html”) #1 data = Context({ ’foo’: ’hello’, ’bar’: ’world’ }) #2 output = template.render(data) #3 returnHttpResponse(output) #4
Renderingshortcuts • HttpResponsesaresimilar in mostviews • Weusuallyrender a template, return an objectorraise an error • Shortcutsavailable in moduledjango.shortcuts • render_to_response • redirect • get_object_or_404, get_list_or_404 • More info: • http://docs.djangoproject.com/en/dev/topics/http/shortcuts/
UsefulLinks • DjangoTutorial • http://docs.djangoproject.com/en/dev/intro/tutorial01/ • T-106.4300 Web Software Developmentslides • MoreextendedinformationaboutDjango • Basics of Python • https://noppa.tkk.fi/noppa/kurssi/t-106.4300/etusivu • Djangodocumentation • http://docs.djangoproject.com/en/1.2/
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)
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
References • Djangodocumentation • http://docs.djangoproject.com/en/1.2/ • T-106.4300 Web Software Developmentslides • Seppala & Karavirta, 2010 • https://noppa.tkk.fi/noppa/kurssi/t-106.4300/etusivu
Installing Google AppEngine • 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) existsbeforestarting to install the SDK • Registeryour Google account in Google AppEngine and create an application
The DjangoHelper for GAE • Download the DjangoHelper for GAE • http://code.google.com/p/google-app-engine-django/ • Decompress the file • Rename the decompresseddirectorywithyourprojectname • Openapp.yaml and change the applicationfield to yourproject Application: mysite
SupportingDjango • Get a Django version • http://www.djangoproject.com/download/ • Decompress the file and copy the djangofolder into yourprojectdirectory • NowyoucancreateDjangoapps inside yourproject >> django-admin.py startappmyapp
DefiningModels Standard Django Django in GAE fromappengine_django.models import BaseModel fromgoogle.appengine.ext import db classPoll(BaseModel): question = db.StringProperty() pub_date = db.DateTimeProperty('datepublished') classChoice(BaseModel): poll = db.ReferenceProperty(Poll) choice = db.StringProperty() votes = db.IntegerProperty() fromdjango.db import models classPoll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('datepublished') classChoice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField()
UsingModelswith Google Datastore • New classes and commands for databasequeries • Query • GqlQuery • Widervariety of data types • http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html • It is notnecessary to buildtablesexplicitely • Commandssyncdb, validate and sql* for manage.pybecomeuseless • More info: • http://code.google.com/appengine/docs/python/datastore/
StoringStaticContent • Images, JavaScript files, CSS templates, etcgetstoredbydefault in a directorystatic inside yourprojectdirectory • The directorystaticneeds to becreated • To changethisdefault, change the followinglines in app.yamlin the handlerssection • url: /static • static_dir: static
Routing • Donealso in the handlerssection of app.yaml • By defaultitfollowswhatyouindicate in yoururls.py • Youcancontrolotheraspectsabout the URLs • Secureaccessthrough HTTPS • Authenticatedaccess • More info: http://code.google.com/appengine/docs/python/config/appconfig.html • url: /.* • script: main.py
UpdatedDjangoSettings • The helperchangessomesettings 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'
Importing the Project • In the Google AppEngineLauncher • File -> AddExistingApplication • Addyourprojectdirectory
References • Google AppEnginedocumentation for Python • http://code.google.com/appengine/docs/python/ • Google AppEngineHelper for Djangodocumentation • http://code.google.com/appengine/articles/appengine_helper_for_django.html