T-110.5130 Mobile Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com - PowerPoint PPT Presentation

minya
slide1 n.
Skip this Video
Loading SlideShow in 5 Seconds..
T-110.5130 Mobile Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com PowerPoint Presentation
Download Presentation
T-110.5130 Mobile Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com

play fullscreen
1 / 42
Download Presentation
T-110.5130 Mobile Systems Programming Alberto Vila Tena alberto.vilatena (at) gmail ( dot ) com
150 Views
Download Presentation

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

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. T-110.5130 Mobile SystemsProgramming Alberto Vila Tena alberto.vilatena(at)gmail(dot)com 28/01/2011

  2. Whatis Django? • Whatis Django? • A Web Application Framework based in Python • And whatis a Web Application Framework? • Anabstraction • Providesgenericfunctionalitycommontomost web applications • Helpsdevelopersbuild 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. Projectsandapps • Project: Collection ofconfigurationsandappsfor a particular website • App: A webapplicationwith a concrete function • A project can containmanyapps • Anapp can be partofmultipleprojects

  6. Creating a Django Project • Creates a directorymysitewiththefollowingstructure >> django-admin.pystartprojectmysite /mysite __init__.py manage.py settings.py urls.py

  7. 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»

  8. Project Settings «settings.py» • Databasesettings • Templatedirectories • Installedapps • Manyothersettings • http://docs.djangoproject.com/en/dev/ref/settings/ • You can alsoaddyourownsettings

  9. 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

  10. 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)), )

  11. Creating a DjangoApp • Creates a directorymyappwiththefollowingstructure >> django-admin.py startappmyapp /myapp __init__.py models.py tests.py views.py

  12. Django Models«models.py» • Describe the data layout of theapplication • Applyintegritychecks • Use Object-RelationalMapping • Simplifiesthedatabasedefinition • Hidesthedatabaseimplementation

  13. Object-relationalMapping • Mapsdatabasetuples into objects • Tablesmapped into classes • Provides • Data Consistency • Databaseindependence • Morevariety and abstraction in data types

  14. 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/

  15. 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()

  16. DjangoTemplates • Documents in a textformatwithpython block tags • {{ variable }} • {{#comment#}} • {{% code %}} • Templatesseparatepresentationfromcontent • Minimizescoupling • Changes in thepresentation do notaffectthecontent • Support HTML, XML, RSS…

  17. 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/

  18. TemplateInheritance • {% extends «template» %} • Inherits the content of an alreadyexistingtemplate • {% block «blockname» %} … {% endblock %} • Definescodeblocks in the parenttemplate • Theseblockscouldbeoverwritten in the childtemplates

  19. Django Views«views.py» • Receive and HttpRequestobject • Define thebusinesslogic of theelementsthey show • ReturnanHttpResponseobject

  20. 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/

  21. 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/

  22. RenderingTemplatesfromViews • Fetch a template • Wrap the data to beshown in a Contextobject • Render the templateusing the data • Return the renderedtemplate as the HttpResponse

  23. RenderingExample defexample_view: template = get_template(”mytemplate.html”) #1 data = Context({ ’foo’: ’hello’, ’bar’: ’world’ }) #2 output = template.render(data) #3 returnHttpResponse(output) #4

  24. 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/

  25. 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/

  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 • 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

  29. Google App Engine

  30. 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

  31. Installing Google AppEngine (II)

  32. FirstExecution of the Launcher

  33. 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

  34. 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

  35. 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()

  36. 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/

  37. 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

  38. 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

  39. 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'

  40. Importing the Project • In the Google AppEngineLauncher • File -> AddExistingApplication • Addyourprojectdirectory

  41. 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

  42. ThankYou! 