際際滷

際際滷Share a Scribd company logo
The Web framework for perfectionists with
              deadlines.
Filosofie
   Loose coupling
   Quick Development
   Don't Repet Yourself (DRY)
   Batteries included :)
Sou叩sti
   URL resolver
   ORM
   Forms
   Templates
   Test framework
   Contrib aplikace
     auth, admin, sessions, formtools
   Reusable aplikace, Pinax
Terminologie
   Model  objekt v DB (User, Article)
   View  k坦d obstar叩vaj鱈c鱈 logiku (list_users(),
    add_article())
   Template  邸ablona presentace (user_list.html)
   Projekt  skupina aplikac鱈, definuje DB a spol.
    (portal, blog), reprezentuje jeden web
   Aplikace  skupina model哲 a pidru転en箪ch
    objekt哲, m哲転e 転鱈t mimo projekt ( comments,
    galleries,articles)
Core
Z叩klad syst辿mu se star叩 o:
   Interakci s web serverem
       mod_python, FastCGI, WSGI
   Zabalen鱈 HTTP po転adavku/odpovdi
   H叩ky pro uchycen鱈 vlastn鱈ho k坦du
       signals    ud叩losti, na kter辿 se d叩 nav叩zat
       middleware  umo転uje vsunout k坦d do
        r哲zn箪ch 叩st鱈 cyklu
Views
   Libovoln叩 funkce pij鱈maj鱈c鱈 HttpRequest a
    vracej鱈c鱈 HttpResponse
def hello_world( request ):
      return HttpResponse( "Hello world!" )


def working( request, id )
      return HttpResponse(
          str(get_object_or_404(Author, pk=id))
      )
URL Resolver (1)
   Pekl叩d叩 URL do vol叩n鱈 view
   Mapov叩n鱈 pomoc鱈 regul叩rn鱈ch v箪raz哲
       skupiny v reg. v箪razech obsahuj鱈 parametry
        funkce
urlpatterns = patterns('user_app',
    url(/slideshow/django-4204103/4204103/r& ),
    url(/slideshow/django-4204103/4204103/r&)/$','detail',
          {'t':'u.html'}),
    url(/slideshow/django-4204103/4204103/r&)),
)
URL Resolver (2)

   Parametry v URL umo転uj鱈 pkn辿 adresy
       /mail/vokurka/inbox/page3/
   Parametry v urlpatterns pom叩haj鱈 u obecn箪ch
    funkc鱈

    include()   pom叩h叩 s modularizac鱈
   Lze mapovat i zptn (view -> URL)
ORM (1)

   PostgreSQL, MySQL, SQLite, Oracle ...
   Umo転uje deklarativn鱈 definici model哲
   Podporuje ddinost (ist)
   Django samo vytvo鱈 DB sch辿ma
   Lazy evaluace dotaz哲
ORM (2) - model
class User( models.Model ):
    name = models.CharField(maxlength=100,
                  unique=True)
    email = models.EmailField(blank=True)
    photo = models.ImageField(
                upload_to='img', blank=True)
    created = models.DateTimeField(
                  default=datetime.now)
    group = models.ForeignKey(Group,
                  blank=True, null=True)

   class Meta:
       ordering = ['name', '-email']
       verbose_name = 'User of our system'
ORM (3) - basic

>>> user = User( name='vomacka' )
>>> user.save()
>>> user.id
1
>>> user.created.year, user.created.month
(2007, 2)
ORM (4) - queryset
>>> qset = User.objects.all()
>>> qset = qset.filter( name__contains='vom')
>>> qset = qset.filter( group__isnull=False,
                     group__created__gt=now() )
>>> qset = qset.order_by( 'created' )
>>> qset.get( pk=1 )
<User: 1>
>>> qset = qset.exclude( name='vokurka' )
>>> qset[:5]
[<User: 1>]
>>> qset.values('email')
[{'email' : 'vomacka@centrum.cz'}]
Templates (1)
Jednoduch箪 znakovac鱈 jazyk:
 {% extends "base.html" %}
 {% block main %}
   {% if user %}
     {{ user.name }}, today is {% now "l" %}.
   {% else %}
     Stranger, this month is {% now "F" %}
   {% endif %}

   {% for obj in object_list %}
     {{ object|escape|urlize }}<br />
   {% endfor%}
 {% endblock %}
Templates (2)
   Zalo転en箪 na ddinosti (include lze tak辿)
   Vyu転鱈v叩 promnn辿 ({{ ... }}) a tagy ({%  %})
       {{ prom.x }}   vyzkou邸鱈 prom.x, prom.x() a
        prom[x]
   Promnn辿 lze pelo転it pomoc鱈 filtr哲
    {{ user.created|date:"F Y" }}
   Soubory se hledaj鱈 dle konfigurace, nap鱈klad:
      v adres叩i templates/ v projektu a aplikac鱈ch
      v datab叩zi
      pes HTTP z jin辿ho serveru
Forms (1)

   Deklarativn鱈 popis formul叩e
   Postar叩 se o validaci a vyi邸tn鱈 dat
   Mo転nost vygenerovat formul叩 pro Model
class MyForm( forms.Form ):
  email = forms.EmailField( required=False )
  choice = forms.ChoiceField(
           choices=[(1,'one'), (2,'two')] )
Forms (2)
Template (easy verze)
  <form action="." method="POST">
    <table>{{ form.as_table }}</table>
    <input type="submit" />
  </form>
View
def my_view( request ):
  if request.method == 'POST':
      form = MyForm( request.POST )
  else: form = MyForm()
  if form.is_valid():
    form.cleaned_data['email']
    return HttpResponseRedirect('/')
  return render_to_response('template.html',
                 {'form' : form})
Dal邸鱈 sou叩sti
   Sessions
   Auth
   Generic Views
   Admin
   Syndication
   GeoDjango
   Comments
   ...
Generic Views (1)
Nkter辿 jednoduch辿 vci se dlaj鱈 st叩le dokola:
   Pid叩n鱈/炭prava/odstrann鱈 objektu
   V箪pis seznamu/podrobnost鱈
   Archiv
Django pro n nab鱈z鱈 hotov辿 view, kter箪m sta鱈
 nastavit parametry
Generic Views (2)
urls.py:
(r'list/$', 'object_list', {'queryset' : qset,
  'paginate_by' : 20} ),

(r'(?P<object_id>d+)/$'), 'object_detail',
  {'queryset' : qset} ),

(r'add/$', 'create_object', {'model' : Model,
  'template_name' : 'model_form.html'} ),

(r'(?P<object_id>d+)/edit/$'), 'update_object',
  {'model' : Model} ),

(r'(?P<object_id>d+)/delete/$'), 'delete_object',
  {'model' : Model} ),
Sessions
   P鱈davn叩 aplikace staraj鱈c鱈 se o zpr叩vu session
    promnn箪ch
   Ve view viditeln辿 jako request.session
   Implementov叩no nkolik backend哲 ( cache,
    db, ...), do request se dostane pes middleware
   Umo転uje ukl叩d叩n鱈 libovoln辿ho obsahu
    (autoatick叩 serializace)
Auth
   Star叩 se o autentifikaci a autorizaci u転ivatel哲
   Mo転no pou転鱈t libovoln箪 backend
   Automaticky vytvo鱈 ADD/UPDATE a DELETE pr叩va
    k model哲m
   Sou叩st鱈 je middleware, kter箪 udr転uje user v
    request.user (pou転鱈v叩 sessions)

    >>> user.is_authenticated()
    True
    >>> user.has_perm('some_perm')
    True
    >>> user.password
    u'sha1$9bb2c$154ecb89654d90a50869c9f115...'
Admin (1)
   Pou転鱈v叩 auth pro spr叩vu u転ivatel哲 a pr叩v
     U転ivatel mus鱈 m鱈t is_staff
     Modely, na kter辿 nem叩 pr叩vo ani nevid鱈
   Umo転uje jednoduch辿 manipulace s objekty
        CREATE/UPDATE/DELETE
   Poskytuje i z叩kladn鱈 dokumentaci k projektu
Admin (2)

class Author( models.Model ):
    name = 
class AuthorOptions(admin.ModelAdmin):
    list_display = ('name', 'surname', 'created' )
    list_filter = ('created', 'site' )
    search_fields = ('name','surname','site__title')
    fields = (
      (None, {'fields':(('name','surname'), 'email'}),
    )
admin.site.register(Author, AuthorOptions)
GeoDjango

   Podpora pro pr叩ci s geografick箪mi daty
   MySQL, Postgres, SQLite, Oracle
   Spatial queries
   Map widget
Reusable Aplikace

   Znovupou転iteln辿 aplikace pro ka転d箪 den:
      Celery (task queues)
      Haystack (fulltext s ruzn箪mi backendy)
      Taggit (tagging)
      Mailer
   Pinax
Zdroje
   http://www.djangobook.com/
   http://code.djangoproject.com/
   http://docs.djangoproject.com/
   Mailing listy
       django-users, django-cs a django-developers
        @googlegroups.com
   IRC: #django on freenode.net
?
Google App Engine
App hosting
   U転ivatel v哲bec nevid鱈 HW
   Nahraje jen aplikaci a pou転鱈v叩 slu転by
   Aplikace v Pythonu nebo Jav (JVM)
   Plat鱈 se za spotebovan辿 prostedky:
          Bandwidth
          CPU time
          Storage
          API calls
Slu転by
   Static files         URL Fetch
   Data Store           Google accounts
   memcached            Cron jobs
   Mail                 Tasks
   XMPP                 Blobstore
   Images
Data store
   NOSQL datab叩ze (GQL)
   Definice model哲, entit, podobn jako v
    Djangu
   Omezen辿 mo転nosti dotaz哲
Models
from google.appengine.ext import db
from google.appengine.api import users
class Employee(db.Model):
  name = db.StringProperty(required=True)
  role = db.StringProperty(required=True,
    choices=set(["executive", "manager",]))
  hire_date = db.DateProperty()
  account = db.UserProperty()

e = Employee(
  name="",
  role="manager",
  account=users.get_current_user())
e.put()
GQL
from google.appengine.api import users

training_registration_list = [
  users.User("Alfred.Smith@example.com"),
  users.User("jharrison@example.com"),
  users.User("budnelson@example.com")]
employees = db.GqlQuery("""
     SELECT *
     FROM Employee
     WHERE account IN :1
  """,
  training_registration_list)
for e in employees: ...
Queries
q = Person.all()
q.filter("last_name =", "Smith")
q.filter("height <", 72)
q.order("-height")

q = db.GqlQuery("""
    SELECT * FROM Person
    WHERE
      last_name = :1 AND height < :2
    ORDER BY height DESC
  """,
  "Smith", 72)
Django on GAE

   GAE m叩 built-in django 0.96, 1.0 a 1.1
      ist辿 django, tedy bez modelu, auth a admin
   djangoappengine (django-nonrel)
     Funkn鱈 admin
   Django NOSQL GSOC
?
Dkuji za pozornost




E-mail: honza.kral@gmail.com
Twitter: @honzakral

More Related Content

Django

  • 1. The Web framework for perfectionists with deadlines.
  • 2. Filosofie Loose coupling Quick Development Don't Repet Yourself (DRY) Batteries included :)
  • 3. Sou叩sti URL resolver ORM Forms Templates Test framework Contrib aplikace auth, admin, sessions, formtools Reusable aplikace, Pinax
  • 4. Terminologie Model objekt v DB (User, Article) View k坦d obstar叩vaj鱈c鱈 logiku (list_users(), add_article()) Template 邸ablona presentace (user_list.html) Projekt skupina aplikac鱈, definuje DB a spol. (portal, blog), reprezentuje jeden web Aplikace skupina model哲 a pidru転en箪ch objekt哲, m哲転e 転鱈t mimo projekt ( comments, galleries,articles)
  • 5. Core Z叩klad syst辿mu se star叩 o: Interakci s web serverem mod_python, FastCGI, WSGI Zabalen鱈 HTTP po転adavku/odpovdi H叩ky pro uchycen鱈 vlastn鱈ho k坦du signals ud叩losti, na kter辿 se d叩 nav叩zat middleware umo転uje vsunout k坦d do r哲zn箪ch 叩st鱈 cyklu
  • 6. Views Libovoln叩 funkce pij鱈maj鱈c鱈 HttpRequest a vracej鱈c鱈 HttpResponse def hello_world( request ): return HttpResponse( "Hello world!" ) def working( request, id ) return HttpResponse( str(get_object_or_404(Author, pk=id)) )
  • 7. URL Resolver (1) Pekl叩d叩 URL do vol叩n鱈 view Mapov叩n鱈 pomoc鱈 regul叩rn鱈ch v箪raz哲 skupiny v reg. v箪razech obsahuj鱈 parametry funkce urlpatterns = patterns('user_app', url(/slideshow/django-4204103/4204103/r& ), url(/slideshow/django-4204103/4204103/r&)/$','detail', {'t':'u.html'}), url(/slideshow/django-4204103/4204103/r&)), )
  • 8. URL Resolver (2) Parametry v URL umo転uj鱈 pkn辿 adresy /mail/vokurka/inbox/page3/ Parametry v urlpatterns pom叩haj鱈 u obecn箪ch funkc鱈 include() pom叩h叩 s modularizac鱈 Lze mapovat i zptn (view -> URL)
  • 9. ORM (1) PostgreSQL, MySQL, SQLite, Oracle ... Umo転uje deklarativn鱈 definici model哲 Podporuje ddinost (ist) Django samo vytvo鱈 DB sch辿ma Lazy evaluace dotaz哲
  • 10. ORM (2) - model class User( models.Model ): name = models.CharField(maxlength=100, unique=True) email = models.EmailField(blank=True) photo = models.ImageField( upload_to='img', blank=True) created = models.DateTimeField( default=datetime.now) group = models.ForeignKey(Group, blank=True, null=True) class Meta: ordering = ['name', '-email'] verbose_name = 'User of our system'
  • 11. ORM (3) - basic >>> user = User( name='vomacka' ) >>> user.save() >>> user.id 1 >>> user.created.year, user.created.month (2007, 2)
  • 12. ORM (4) - queryset >>> qset = User.objects.all() >>> qset = qset.filter( name__contains='vom') >>> qset = qset.filter( group__isnull=False, group__created__gt=now() ) >>> qset = qset.order_by( 'created' ) >>> qset.get( pk=1 ) <User: 1> >>> qset = qset.exclude( name='vokurka' ) >>> qset[:5] [<User: 1>] >>> qset.values('email') [{'email' : 'vomacka@centrum.cz'}]
  • 13. Templates (1) Jednoduch箪 znakovac鱈 jazyk: {% extends "base.html" %} {% block main %} {% if user %} {{ user.name }}, today is {% now "l" %}. {% else %} Stranger, this month is {% now "F" %} {% endif %} {% for obj in object_list %} {{ object|escape|urlize }}<br /> {% endfor%} {% endblock %}
  • 14. Templates (2) Zalo転en箪 na ddinosti (include lze tak辿) Vyu転鱈v叩 promnn辿 ({{ ... }}) a tagy ({% %}) {{ prom.x }} vyzkou邸鱈 prom.x, prom.x() a prom[x] Promnn辿 lze pelo転it pomoc鱈 filtr哲 {{ user.created|date:"F Y" }} Soubory se hledaj鱈 dle konfigurace, nap鱈klad: v adres叩i templates/ v projektu a aplikac鱈ch v datab叩zi pes HTTP z jin辿ho serveru
  • 15. Forms (1) Deklarativn鱈 popis formul叩e Postar叩 se o validaci a vyi邸tn鱈 dat Mo転nost vygenerovat formul叩 pro Model class MyForm( forms.Form ): email = forms.EmailField( required=False ) choice = forms.ChoiceField( choices=[(1,'one'), (2,'two')] )
  • 16. Forms (2) Template (easy verze) <form action="." method="POST"> <table>{{ form.as_table }}</table> <input type="submit" /> </form> View def my_view( request ): if request.method == 'POST': form = MyForm( request.POST ) else: form = MyForm() if form.is_valid(): form.cleaned_data['email'] return HttpResponseRedirect('/') return render_to_response('template.html', {'form' : form})
  • 17. Dal邸鱈 sou叩sti Sessions Auth Generic Views Admin Syndication GeoDjango Comments ...
  • 18. Generic Views (1) Nkter辿 jednoduch辿 vci se dlaj鱈 st叩le dokola: Pid叩n鱈/炭prava/odstrann鱈 objektu V箪pis seznamu/podrobnost鱈 Archiv Django pro n nab鱈z鱈 hotov辿 view, kter箪m sta鱈 nastavit parametry
  • 19. Generic Views (2) urls.py: (r'list/$', 'object_list', {'queryset' : qset, 'paginate_by' : 20} ), (r'(?P<object_id>d+)/$'), 'object_detail', {'queryset' : qset} ), (r'add/$', 'create_object', {'model' : Model, 'template_name' : 'model_form.html'} ), (r'(?P<object_id>d+)/edit/$'), 'update_object', {'model' : Model} ), (r'(?P<object_id>d+)/delete/$'), 'delete_object', {'model' : Model} ),
  • 20. Sessions P鱈davn叩 aplikace staraj鱈c鱈 se o zpr叩vu session promnn箪ch Ve view viditeln辿 jako request.session Implementov叩no nkolik backend哲 ( cache, db, ...), do request se dostane pes middleware Umo転uje ukl叩d叩n鱈 libovoln辿ho obsahu (autoatick叩 serializace)
  • 21. Auth Star叩 se o autentifikaci a autorizaci u転ivatel哲 Mo転no pou転鱈t libovoln箪 backend Automaticky vytvo鱈 ADD/UPDATE a DELETE pr叩va k model哲m Sou叩st鱈 je middleware, kter箪 udr転uje user v request.user (pou転鱈v叩 sessions) >>> user.is_authenticated() True >>> user.has_perm('some_perm') True >>> user.password u'sha1$9bb2c$154ecb89654d90a50869c9f115...'
  • 22. Admin (1) Pou転鱈v叩 auth pro spr叩vu u転ivatel哲 a pr叩v U転ivatel mus鱈 m鱈t is_staff Modely, na kter辿 nem叩 pr叩vo ani nevid鱈 Umo転uje jednoduch辿 manipulace s objekty CREATE/UPDATE/DELETE Poskytuje i z叩kladn鱈 dokumentaci k projektu
  • 23. Admin (2) class Author( models.Model ): name = class AuthorOptions(admin.ModelAdmin): list_display = ('name', 'surname', 'created' ) list_filter = ('created', 'site' ) search_fields = ('name','surname','site__title') fields = ( (None, {'fields':(('name','surname'), 'email'}), ) admin.site.register(Author, AuthorOptions)
  • 24. GeoDjango Podpora pro pr叩ci s geografick箪mi daty MySQL, Postgres, SQLite, Oracle Spatial queries Map widget
  • 25. Reusable Aplikace Znovupou転iteln辿 aplikace pro ka転d箪 den: Celery (task queues) Haystack (fulltext s ruzn箪mi backendy) Taggit (tagging) Mailer Pinax
  • 26. Zdroje http://www.djangobook.com/ http://code.djangoproject.com/ http://docs.djangoproject.com/ Mailing listy django-users, django-cs a django-developers @googlegroups.com IRC: #django on freenode.net
  • 27. ?
  • 29. App hosting U転ivatel v哲bec nevid鱈 HW Nahraje jen aplikaci a pou転鱈v叩 slu転by Aplikace v Pythonu nebo Jav (JVM) Plat鱈 se za spotebovan辿 prostedky: Bandwidth CPU time Storage API calls
  • 30. Slu転by Static files URL Fetch Data Store Google accounts memcached Cron jobs Mail Tasks XMPP Blobstore Images
  • 31. Data store NOSQL datab叩ze (GQL) Definice model哲, entit, podobn jako v Djangu Omezen辿 mo転nosti dotaz哲
  • 32. Models from google.appengine.ext import db from google.appengine.api import users class Employee(db.Model): name = db.StringProperty(required=True) role = db.StringProperty(required=True, choices=set(["executive", "manager",])) hire_date = db.DateProperty() account = db.UserProperty() e = Employee( name="", role="manager", account=users.get_current_user()) e.put()
  • 33. GQL from google.appengine.api import users training_registration_list = [ users.User("Alfred.Smith@example.com"), users.User("jharrison@example.com"), users.User("budnelson@example.com")] employees = db.GqlQuery(""" SELECT * FROM Employee WHERE account IN :1 """, training_registration_list) for e in employees: ...
  • 34. Queries q = Person.all() q.filter("last_name =", "Smith") q.filter("height <", 72) q.order("-height") q = db.GqlQuery(""" SELECT * FROM Person WHERE last_name = :1 AND height < :2 ORDER BY height DESC """, "Smith", 72)
  • 35. Django on GAE GAE m叩 built-in django 0.96, 1.0 a 1.1 ist辿 django, tedy bez modelu, auth a admin djangoappengine (django-nonrel) Funkn鱈 admin Django NOSQL GSOC
  • 36. ?
  • 37. Dkuji za pozornost E-mail: honza.kral@gmail.com Twitter: @honzakral