Introduce Django

  • 2,628 views
Uploaded on

 

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,628
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
70
Comments
0
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • Django follows Python's core concept of keeping things as simple as possible and understandable. This leads to much more maintainable code in the future. Libraries play a huge part in choosing Django over Rails. Python has a library for just about everything Basically coding practices which help you put together some quick, clever code. This is nice, but much like Perl code it can end up making code a PITA to maintain. I cannot express how much better this is than than anything Ruby has. Ruby's module system doesn't even come close.
  • http:// wiki.rubyonrails.org/.../UnderstandingRailsMVC http://dotsx.usc.edu/rails2.png
  • http://www.phpwact.org/pattern/model_view_controller?DokuWiki=01b5b5ce30eea3c7558b04b1d02ae25c
  • http://en.wikipedia.org/wiki/Web_template http://en.wikipedia.org/wiki/Web_template_system_%28terminology%29

Transcript

  • 1. Introduce Django The Python Web Framework [email_address]
  • 2. Web “ Framework ” ?
    • A web application framework is a set of software tools and libraries to make it easier to create web applications. They typically provide functionality such as database access, templating and session management.
    • -- Wikipedia
  • 3. Please Teach me Web Frameworks for Python!
    • Guido van Rossum , Jan 27, 2006
    • “”” After years of resistance, I'm finally finding myself building a web application again. I think the last time I did that was the "faq wizard" which still lives in Python's Tools directory. It was a CGI script …….”””
  • 4. Which Part of "No XML" Don't You Understand?
    • Guido van Rossum, January 31, 2006
    • The XML crowd don't seem to get it. I don't *want* to use XML in my templates. Now can they leave me alone and stop telling me that I want XML?
    • I'm not saying that there's no use for XML. But if you see XML as the solution to every problem, well, that's a problem.
  • 5. Django
    • Oh My God It's Django!
    • August 17th, 2006
    • Guido just pronounced: Django is the web framework
    • Won't be part of the core, but will be as 「 standard 」 as PIL or NumPy
    • He hopes that Django and TurboGears will converge
  • 6. Popular Web Framework Today (via lang)
    • Java: , Spring , WebWork, Tapestry, JSF
    • PHP:       , CakePHP , Code Igniter, Zend Framework
    • Perl: , Maypole
    • Python: ,TurboGears ,Pylons
    • Ruby: , Nitro
  • 7. Chapter 1: The buzz words Why Django over other web frameworks.
  • 8. Why Django?
    • http://www.djangoproject.com/weblog/2006/dec/06/comparisons/
    • Person 1: "What do you do for a living?"
    • Person 2: "I work with computers."
    • Person 1: "So do I! What do you do with computers?"
    • Person 2: "I'm a Web developer."
    • Person 1: "So am I! Design, client-side programming or server-side programming?"
    • Person 2: "Server-side programming."
  • 9. Why Django? [cont.]
    • Person 1: "Same here! Do you use dynamically typed languages or statically typed languages?"
    • Person 2: "Dynamically typed languages."
    • Person 1: "So do I! Do you use a Web framework, or do you roll things on your own?"
    • Person 2: "I use a Web framework."
  • 10. Why Django? [cont.]
    • Person 1: "So do I! Django or Rails? "
    • Person 2: "Django."
    • Person 1: "Die, heretic scum! “
    • ( 去死吧 異教徒雜碎 )
  • 11. Warning…
    • One thing is clear, though: everyone's getting stuff done, regardless of their language choice. The whole debate isn't actually about productivity at all, even though most people still think it is. It's about whether you can stand to live in a house where the bed isn't made.
      • -- Steve Yegge
  • 12. Dr. Larson's renowned treatise on non-inferring static type systems http://steve-yegge.blogspot.com/2006_10_01_archive.html
  • 13. Why Django #1 : Python
    • http://jesusphreak.infogami.com/blog/why_django
    • Simple as possible
    • Libraries.
    • Ruby programming tends to favor 'magic'.
    • Python's package system makes organizing your code so much easier.
  • 14. Why Django #2: Documentation
    • Every new Rails developer is told to pickup a copy of Agile Web Development for Rails .
    • The Django Book , which is currently being developed with the help of the community, and will be available online for free.
  • 15. Why Django #3: Templating
    • The Author initially really disliked the Django templating system. (same to me!)
    • Couldn't jam application code into the template. It truly restricted to only formatting content.
    • if you couldn't express something with the template system, you was doing something wrong.
  • 16. Other reasons … (django over rails)
    • #4: Speed
    • #5: Admin interface
    • #6: Generic views
    • #7: Simplicity and flexibility
    • #8: Reality, not buzz-words
    • Comment from me: However, Rails is indeed a great web framework if you like know ruby (a lot).
  • 17. Web Framework Performance Compare (at rails wiki)
    • http://wiki.rubyonrails.com/rails/pages/Framework+Performance
      • Summary
      • Rails performed much better than Symfony. And Django performed much better than Rails.
  • 18. Comment at Catalyst User ‘ s blog
    • http://letsgetdugg.com/view/Catalyst_vs_Rails_vs_Django_Cook_off
    • “”” Today I began working on a new project and decided to benchmark Catalyst and Rails for fun. See how my new favorable framework does against Rails.
    • Conclusion: It seems like Rails is roughly 62% faster than Catalyst at this time. … . (Django) Amazing and the winner ! I have the least experience with django for your information, mst Please don't kill me ””
  • 19. Django Design philosophies
    • Loose coupling
    • Quick development
    • Don't repeat yourself (DRY)
    • Explicit is better than implicit
    • Consistency / Less code
    • http://www.djangoproject.com/documentation/design_philosophies/
  • 20. Chapter 2: Django Overview Django Web Framework 101
  • 21.  
  • 22. MVC,MTV – if it walks like a duck …
    • MVC: Model-View-Controller Architecture
    • … it ’ s a duck
    MVC RoR Django Model model model View view template Controller controller view
  • 23. Web Server Browser/Client URL Dispatcher: URLconf => urls.py View ( controller ) : views.py Model : models.py Database (mysql, postgresql, sqlite) Template HTML/XHTML CSS/Image Javascript settings.py manage.py django-admin.py Admin Generic View Request Response
  • 24. How Django place files
    • Database Wrapper model.py
    • Admin Framework  add class Admin declare in model.py
    • Controller  view.py
    • URL dispatcher  url.py
    • Template System index.html
    • settings.py manage.py django-admin.py are just helper.
  • 25. Template: Client-side Logic such as date format 18/12/2006" or "2006-12-18" presentation need to solved without breaking the separation strategy HTML/XHTML CSS Javascript Structure : What Does it MEAN? Presentation :What does it LOOK like? Behavior : What Does it Do ? View(Controller): Server-side Logic Content: Django is for backend. You still have to know XHTML/CSS/Javascript for your front-end needs. The View in MVC isn’t easy as you might think
  • 26. Still something great …
    • Cache system
    • Internationalization
    • Middleware (Add-ons)
    • Sessions / Cookies
    • New Form (in svn / not in 0.95 Release)
  • 27. Chapter 3: Hello, Django write a web announce system
  • 28. I’ll show you…(the core idea)
    • Object-relational mapper (ORM)
    • Automatic admin interface
    • Elegant URL design
    • Designer-friendly Template system
    • With 8 step (9 pages of slides) !
  • 29. Follow me. #1: Start project
    • apt-get install django (or something like that)
    • django-admin.py startproject superhard
    • superhard/
    • __init__.py
    • manage.py
    • settings.py
    • urls.py
  • 30. Follow me #2: Create application
    • cd superhard
    • python manage.py startapp announce
    • superhard/announce/
    • __init__.py
    • models.py
    • views.py
  • 31. Follow me #3: Create Database
    • Edit settings.py
    • DATABASE_ENGINE : sqlite3
    • DATABASE_NAME :msg.db
    • apt-get install pysqlite2 sqlite3
    • python manage.py syncdb
    • # also create a superuser
  • 32. Follow me #4: build your model
    • superhard/announce/models.py
    • from django.db import models #auto generate
    • class Msg(models.Model):
    • name = models.CharField(maxlength=64)
    • date = models.DateTimeField('postdate')
    • msgtxt = models.TextField(maxlength=8192)
    • class Admin:
    • pass
  • 33. Follow me #5: Write Your Template
    • Edit TEMPLATE_DIRS in your settings.py
    • Don ’ t put template in your www directory.
    • superhard-template/announce_list.html
      • <html><head><title>test</title></head><body>
      • #(insert template code here)
      • </body>
    • </html>
  • 34. Follow me #5: Write Your Template (cont.)
    • {%if msgs_list %}
    • {% for msg in msgs_list %}
    • <p> {{ msg.name }} at {{msg.date}} </p>
    • <p> {{msg.msgtxt}} </p>
    • {% endfor %}
    • {%else %}
    • <p>No Announce are available now.</p>
    • {%endif %}
  • 35. Follow me #6: Write Your View
    • superhard/announce/views.py :
    • from django.shortcuts import render_to_response
    • from superhard.announce.models import Msg
    • def announce_index(request):
    • latest_msg = Msg.objects.all().order_by('date')[:5]
    • return render_to_response('announce.html', {'msgs_list': latest_msg})
  • 36. Follow me #7: urls.py
    • urlpatterns = patterns(
    • ' superhard.announce.views ',
    • (r ' ^$ ' , ' announce_index ' ) ,
    • ('abc', 'announce_index'),
    • # (r'^admin/', include('django.contrib.admin.urls')),
    • )
    • Uncomment urls for admin
    • django just need an urlpatterns object
  • 37. #8: Let ’ s start play!
    • python manage.py runserver
    • Add 'django.contrib.admin', 'superhard.announce', to your INSTALLED_APPS
    • python manage.py syncdb
    • http://127.0.0.1:8000/
    • http://127.0.0.1:8000/admin
  • 38. Deploy
    • Fastcgi or mod_python
    • Static content should be separate
    • Deploy on web hosting server not as easy as PHP. (for now)
    • But if it works, it works well !
    • Lighttpd with fastcgi should be good.
  • 39. Chapter 4 Generic View
  • 40. Don’t Repeat Yourself (DRY)
    • Generic views let you quickly provide common views of an object without actually needing to write any Python code
    • You don’t really have to write Python code.
    • It’s not MAGIC! Django provide most common patterns and you can extend it.
    • It’s nothing about View in MVC, it’s about reuse controller logic.
  • 41. Reuse your logic
    • &quot;Simple&quot; generic views
    • Date-based generic views
    • List/detail generic views
    • pagination
    • Create/update/delete generic views
    • You could use it in urls.py or views.py
    • Simple logic => just use it in urls.py!
  • 42. Url.py – get rids of views.py
    • from django.conf.urls.defaults import *
    • from superhard2.announce.models import Msg
    • urlpatterns = patterns(
    • 'django.views.generic.list_detail',
    • (r'^$', 'object_list',
    • { 'queryset':Msg.objects.all().order_by('date')[:5],
    • 'template_name':'announce_list.html', #can omit
    • 'template_object_name':'msgs', }),
    • (r'^admin/',include('django.contrib.admin.urls')),
    • )
  • 43. Chapter 5 Real World Code Snippet
  • 44. Welcome to Real World!
    • Real world is messy.
    • Django is easy, but make a good web application is not.
    • You’ll glad you choose python.
    • Django is not perfect, but it’s good enough.
    • Don’t Repeat Yourself (DRY)
  • 45. 1. Table relation.
    • class Stb(models.Model):
    • stbSerial = models.CharField(primary_key=True)
    • stbSubGroupNum = models.ForeignKey('Subgroup')
    • class Subgroup(models.Model):
    • subGroupNum = models.CharField(primary_key=True)
    • pGroup = models.ForeignKey('Pgroup‘)
    • class Pgroup(models.Model)
      • groupNum = models.CharField(primary_key=True)
  • 46. 2. Ajax via simplejson
    • from django.utils import simplejson
    • def ajax_view(request):
    • jsondict = {“a&quot;:request.session[‘a’],“b&quot;:”hi”}
    • return HttpResponse(simplejson.dumps(jsondict))
  • 47. 3. Extend template tags.
    • from django import template
    • register = template.Library()
    • @register.simple_tag
    • def tick_to_time(ticks):
    • import time
    • try:
    • return time.asctime(time.localtime(float(ticks)))
    • except:
    • return ““ #empty string
  • 48. 4. Write your own decorator
    • def login_required(f):
    • def wrap(request, *args, **kwargs):
    • if not request.session or ‘name’ not in request.session.keys():
    • return HttpResponseRedirect(“/login”)
    • return f(request, *args, **kwargs)
    • return wrap
    • @login_required
    • def some_viewfunc_needlogin(request):
    • ……
  • 49. 5. Use Syslog debug production server
    • import syslog
    • error = “what ever you wanna log”
    • syslog.syslog(syslog.LOG_NOTICE,error)
  • 50. Chapter 6 It’s not end…
  • 51. Something you still should learn. (except Python)
    • Django won ’ t magically turn you from newbie to Web pros. It just let your life easier.
    • Learn HTML / XHTML. (learn how to struct)
    • Learn CSS / Javascript and get your firebug. (CSS2.1/Prototype/Dojo/YUI/Mochkit/jQuery).
    • Learn Browser.
    • (IE7, IE6, IE5.5, firefox [gecko], opera, Safari)
    • Learn SQL (learn how to maintain/transfer data)
    • Learn Apache / Http (learn how to scale)
    • Learn You ’ re not genius. Learn from other (genius) people. Don ’ t reinvent a WORSE wheel.
  • 52. Resource:
    • http://www.djangoproject.com/documentation/
    • The Django Book
    • Django Step by Step ( simplified Chinese )
    • 拜 Python 教之 Django 光明會支部
    • http://timchen119.blogspot.com
    • Tim ( 使徒提姆 ) at kalug mailto: [email_address] :P
  • 53.
        • Thanks!