Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

伝説のギタリストじゃない方のDjango

2,053 views

Published on

2006年1月にPythonWorkshop03でDjangoを紹介した時のスライドです。

Published in: Technology
  • Be the first to comment

伝説のギタリストじゃない方のDjango

  1. 1. Django
  2. 2. Django biography Django Reinhardt 1910 Django 2003 2005 7 Rails discography www.ljworld.com www.lawrence.com projects.washingtonpost.com/contress/
  3. 3. main features
  4. 4. main features O/R Mapper Automatic Admin Interface Elegant URL Design Template Cache i18n
  5. 5. O/R Mapper
  6. 6. O/R Mapper DRY Model
  7. 7. O/R Mapper DRY Model Model Database
  8. 8. O/R Mapper DRY Model Model Database SQLObject SELECT keyword args ForeignKey model Index Model
  9. 9. Automatic Admin I/F
  10. 10. Automatic Admin I/F model rails scafford TurboGears catwalk
  11. 11. Automatic Admin I/F model rails scafford TurboGears catwalk
  12. 12. Automatic Admin I/F model rails scafford TurboGears catwalk
  13. 13. Elegant URL Desgin
  14. 14. Elegant URL Desgin URL emacs PROJECT/apps/project/urls.py (r'^Task/(?P<task_id>d+)/edit/$','Project.apps.project.views.edit'), emacs PROJECT/apps/project/views.py def edit(request, task_id) : do_somthing
  15. 15. Elegant URL Desgin URL http://host/WorkStyle/Task/5/edit/ emacs PROJECT/apps/project/urls.py (r'^Task/(?P<task_id>d+)/edit/$','Project.apps.project.views.edit'), emacs PROJECT/apps/project/views.py def edit(request, task_id) : do_somthing
  16. 16. Elegant URL Desgin URL http://host/WorkStyle/Task/5/edit/ 5 emacs PROJECT/apps/project/urls.py (r'^Task/(?P<task_id>d+)/edit/$','Project.apps.project.views.edit'), emacs PROJECT/apps/project/views.py def edit(request, task_id) : do_somthing
  17. 17. Elegant URL Desgin URL emacs PROJECT/apps/project/urls.py (r'^Task/(?P<task_id>d+)/edit/$','Project.apps.project.views.edit'), emacs PROJECT/apps/project/views.py def edit(request, task_id) : do_somthing
  18. 18. Template
  19. 19. Template {{ XXX:escape }} {% if task.update_date %} <tr> <th nowrap="nowrap">{% trans "Last Update" %}</th> <td>{{ task.update_date|date:"Y/m/d" }}</td> </tr> {% endif %}
  20. 20. Template {{ XXX:escape }} {% if task.update_date %} filter <tr> <th nowrap="nowrap">{% trans "Last Update" %}</th> <td>{{ task.update_date|date:"Y/m/d" }}</td> </tr> {% endif %}
  21. 21. Template {{ XXX:escape }} Tag {% if task.update_date %} <tr> <th nowrap="nowrap">{% trans "Last Update" %}</th> <td>{{ task.update_date|date:"Y/m/d" }}</td> </tr> {% endif %}
  22. 22. cache
  23. 23. cache 3 HTTP
  24. 24. Cache cache locmem( WorkStyle sqlite3 SQL 5 O/R :P4-2.4GHz+1GBMem, Gentoo, apache:2.0.54, mod_python3.x :iBookG4-800MHz, 640MBMem, ApacheBench1.3d 1000request 10concurrency
  25. 25. Cache cache locmem( WorkStyle sqlite3 SQL 5 O/R :P4-2.4GHz+1GBMem, Gentoo, apache:2.0.54, mod_python3.x :iBookG4-800MHz, 640MBMem, ApacheBench1.3d 1000request 10concurrency normal apache locmem totaltime 114.98 20.95 5.05 rec/sec 8.7 47.72 197.82
  26. 26. Cache cache locmem( WorkStyle sqlite3 SQL 5 O/R :P4-2.4GHz+1GBMem, Gentoo, apache:2.0.54, mod_python3.x :iBookG4-800MHz, 640MBMem, ApacheBench1.3d 1000request 10concurrency total time Request/sec 200 150 normal apache locmem 100 totaltime 114.98 20.95 5.05 50 rec/sec 8.7 47.72 197.82 0 normal apache locmem
  27. 27. i18n
  28. 28. i18n po settings.py Automatic Admin I/F
  29. 29. i18n po settings.py Automatic Admin I/F code _(“message”) {% trans “message” %} template
  30. 30. i18n po settings.py Automatic Admin I/F po DJANGO_HOME/bin/make-messages.py -l ja DJANGO_HOME/bin/compile-messages.py compile
  31. 31. i18n po settings.py Automatic Admin I/F > emacs settings.py MIDDLEWARE_CLASSES = ( 'django.middleware.locale.LocaleMiddleware', 'django.middleware.sessions.SessionMiddleware', 'django.middleware.common.CommonMiddleware', )
  32. 32. Python2.3 Apache2.x+mod_python3.x fast-cgi(WSGI) PostgreSQL/MySQL/SQLite3/SQLServer
  33. 33. Project Django Model URL view Template
  34. 34. Django Django python manage.py init python manage.py startapp APP Project APP APP python manage.py install APP Project django-admin.py startproject PROJECT APP
  35. 35. NO django-admin.py startproject PROJECT YES Django python manage.py init python manage.py startapp APP emacs app/APP/models/APP.py python manage.py install APP
  36. 36. Project django-admin.py startproject WorkStyle WorkStyle + apps __init__.py __init__.py urls.py settings.py manage.py
  37. 37. Project django-admin.py startproject WorkStyle WorkStyle + apps __init__.py __init__.py urls.py settings.py manage.py Project
  38. 38. > emacs Project/settings.py # 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'. DATABASE_ENGINE = 'postgresql' DATABASE_NAME = 'workstyle' DATABASE_USER = 'workstyle' DATABASE_PASSWORD = 'workstyle' DATABASE_HOST = '' DATABASE_PORT = ''
  39. 39. Django Django python manage.py init ## DJANGO CORE TABLE auth_groups auth_groups_permissions auth_messages auth_permissions auth_users auth_users_groups auth_users_user_permissions content_types core_sessions packages sites
  40. 40. python manage.py startapp workstyle WorkStyle + apps __init__.py + workstyle __init__.py view.py + models __init__.py workstyles.py __init__.py urls.py settings.py manage.py
  41. 41. python manage.py startapp workstyle WorkStyle + apps __init__.py + workstyle __init__.py view.py + models __init__.py workstyles.py __init__.py urls.py settings.py manage.py
  42. 42. python manage.py startapp workstyle WorkStyle + apps __init__.py + workstyle __init__.py view.py + models __init__.py workstyles.py __init__.py urls.py settings.py manage.py
  43. 43. python manage.py startapp workstyle WorkStyle + apps __init__.py + workstyle __init__.py view.py + models __init__.py workstyles.py __init__.py urls.py settings.py manage.py
  44. 44. python manage.py startapp workstyle WorkStyle + apps __init__.py + workstyle __init__.py view.py + models __init__.py workstyles.py __init__.py urls.py settings.py manage.py
  45. 45. python manage.py startapp workstyle WorkStyle + apps __init__.py + workstyle __init__.py view.py + models __init__.py workstyles.py __init__.py urls.py settings.py manage.py
  46. 46. Model Model > emacs Project/apps/workstyle/models/workstyle.py from django.core import meta class Task(meta.Model): task = meta.TextField(db_index=True) create_date = meta.DateTimeField(auto_now_add=True) update_date = meta.DateTimeField() tag_searchable = meta.CharField(maxlength=800, db_index=True, null=True) estimate = meta.FloatField(max_digits=3, default=0, decimal_places=1, null=True) status = meta.IntegerField(maxlength=1, default=3, choices=TASK_STATUS_CHOICES, db_index=True) class META: ordering = ['-update_date']
  47. 47. Model Model meta.Model > emacs Project/apps/workstyle/models/workstyle.py from django.core import meta class Task(meta.Model): task = meta.TextField(db_index=True) create_date = meta.DateTimeField(auto_now_add=True) update_date = meta.DateTimeField() tag_searchable = meta.CharField(maxlength=800, db_index=True, null=True) estimate = meta.FloatField(max_digits=3, default=0, decimal_places=1, null=True) status = meta.IntegerField(maxlength=1, default=3, choices=TASK_STATUS_CHOICES, db_index=True) class META: ordering = ['-update_date']
  48. 48. Model python manage.py install workstyle ## APPLICATION TABLE workstyle_tasks workstyle_tags workstyle_taglists workstyle_comments workstyle_attachments
  49. 49. Model python manage.py install workstyle ## APPLICATION TABLE workstyle_tasks workstyle_tags workstyle_taglists workstyle_comments workstyle_attachments
  50. 50. Model python manage.py install workstyle ## APPLICATION TABLE workstyle_tasks workstyle_tags workstyle_taglists workstyle_comments workstyle_attachments Class
  51. 51. O/R Python > export DJANGO_SETTINGS_MODULE=WorkStyle.settings > python
  52. 52. O/R Python > export DJANGO_SETTINGS_MODULE=WorkStyle.settings > python import django.models.workstyle import tasks, comments #tasks Task workstyle_tasks #(Black Magic) tasks.get_list(**keyargs) # query = {} query[‘status__in’] = [1,2,3] tasks.get_list(**query)
  53. 53. O/R Python > export DJANGO_SETTINGS_MODULE=WorkStyle.settings > python import django.models.workstyle import tasks, comments tsk1 = tasks.get_object(pk=1) #pk tsk1.status = 2 tsk1.save() # tsk2 = tasks.Task(task='hoge',status=2, update_date=datetime.now()) tsk2.save() #
  54. 54. O/R Python > export DJANGO_SETTINGS_MODULE=WorkStyle.settings > python import django.models.workstyle import tasks, comments # tsk.add_comment(comment=in_comment_body, commentator=in_commentator) # 1:n tsk.get_comment_list()
  55. 55. O/R Python > export DJANGO_SETTINGS_MODULE=WorkStyle.settings > python import django.models.workstyle import tasks, comments #join:Comment # Comment get_task SQL comments.get_list(select_related=True)
  56. 56. O/R Python > export DJANGO_SETTINGS_MODULE=WorkStyle.settings > python import django.models.workstyle import tasks, comments #join:Comment # Comment get_task SQL comments.get_list(select_related=True)
  57. 57. URL Dispatcher > emacs Project/urls.py (r'^WorkStyle/', include('WorkStyle.apps.workstyle.urls')), > touch Project/apps/workstyle/urls.py > emacs Project/apps/workstyle/urls.py (r'^Task/(?P<task_id>d+)/edit/$', 'WorkStyle.apps.workstyle.task.edit_task'),
  58. 58. URL Dispatcher > emacs Project/urls.py (r'^WorkStyle/', include('WorkStyle.apps.workstyle.urls')), > touch Project/apps/workstyle/urls.py > emacs Project/apps/workstyle/urls.py (r'^Task/(?P<task_id>d+)/edit/$', 'WorkStyle.apps.workstyle.task.edit_task'),
  59. 59. > emacs WorkStyle/apps/workstyle/task.py def edit_task(request, task_id) : task = get_object_or_404(tasks,pk=task_id) manipulator = tasks.ChangeManiplator() if request.POST : new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if not errors : # return render_to_response(....) else : errors = {} new_data = {'status': str(task.status), 'task': task.task, 'estimate': task.estimate} return render_to_response('workstyle/TaskFormEdit',{'form': form, 'task': task....})
  60. 60. > emacs WorkStyle/apps/workstyle/task.py def edit_task(request, task_id) : task = get_object_or_404(tasks,pk=task_id) manipulator = tasks.ChangeManiplator() if request.POST : new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if not errors : # return render_to_response(....) else : errors = {} new_data = {'status': str(task.status), 'task': task.task, 'estimate': task.estimate} return render_to_response('workstyle/TaskFormEdit',{'form': form, 'task': task....})
  61. 61. Manipulator model Manipulator (Add,Change) def create(request): manipulator = tasks.AddManipulator() new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if errors : # else : manipulator.do_html2python(request.POST) new_task = manipulator.save(request.POST)
  62. 62. Manipulator model Add Change Manipulator (Add,Change) def create(request): manipulator = tasks.AddManipulator() new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if errors : # else : manipulator.do_html2python(request.POST) new_task = manipulator.save(request.POST)
  63. 63. Manipulator validation model errors Manipulator (Add,Change) def create(request): manipulator = tasks.AddManipulator() new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if errors : # else : manipulator.do_html2python(request.POST) new_task = manipulator.save(request.POST)
  64. 64. Manipulator model Manipulator (Add,Change) def create(request): manipulator = tasks.AddManipulator() new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if errors : # else : manipulator.do_html2python(request.POST) new_task = manipulator.save(request.POST)
  65. 65. Manipulator class TaskManipulator(formfields.Manipulator): def __init__(self): self.fields = ( formfields.LargeTextField( field_name="task_tag", validator_list=[self.isValidTagName]), formfields.TextField( field_name="commentator", maxlength=50, is_required=False), formfields.SelectField( field_name="status", choices=TASK_STATUS, is_required=True), ) def isValidTagName(self, field_data, all_data): task_tag_list = string.split(field_data, "]") for task_tag in task_tag_list : task_tag = string.strip(string.replace(task_tag, "[", "")) if len(task_tag) > 49 : raise validators.ValidationError(_("Tag's name is must be less than 50 characters."))
  66. 66. Manipulator #view manipulator = TaskManipulator() try : task = tasks.get_object(pk=task_id) except ObjectDoesNotExist : raise Http404 if request.POST : new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if not errors : return update_task(request, task_id) else :
  67. 67. Template settings.py Template > emacs Project/settings.py TEMPLATE_DIRS = ( WORKSTYLE_BASE_DIR + "/apps/workstyle/templates", )
  68. 68. Template settings.py Template > emacs Project/settings.py TEMPLATE_DIRS = ( WORKSTYLE_BASE_DIR + "/apps/workstyle/templates", ) > emacs Project/apps/workstyle/templates/workstyle/TaskForm.html <div id="main"> {% block formaction %} <form action="{{ workstyle_root }}/Task/{{ task.id }}/update/" name="taskForm" method="POST" enctype="multipart/form-data" class="tableForm" onSubmit="return checkBody();"> {% endblock %} Base
  69. 69. Template settings.py Template > emacs Project/settings.py TEMPLATE_DIRS = ( WORKSTYLE_BASE_DIR + "/apps/workstyle/templates", ) > emacs Project/apps/workstyle/templates/workstyle/TaskFormNew.html {% extends "workstyle/TaskForm" %} {%block formaction %} <form action="{{ workstyle_root }}/Task/add/" name="task_form" method="POST" enctype="multipart/form-data" class="tableForm" onSubmit="return checkBody();"> {% endblock %} New extends Base
  70. 70. Template settings.py Template > emacs Project/settings.py TEMPLATE_DIRS = ( WORKSTYLE_BASE_DIR + "/apps/workstyle/templates", ) > emacs Project/apps/workstyle/templates/workstyle/TaskFormEdit.html {% extends "workstyle/TaskForm" %} {%block formaction %} <form action="{{ workstyle_root }}/Task/{{ task.id }}/update/" name="taskForm" method="POST" enctype="multipart/form-data" class="tableForm" onSubmit="return checkBody();"> {% endblock %} Edit extends Base
  71. 71. > emacs Project/apps/workstyle/templatetags/wsfilter.py from django.core import template register = template.Library() def truncatelines(value, arg) : result = value #do something return result register.filter('truncatelines', truncatelines)
  72. 72. > emacs Porject/apps/workstyle/task.py from WorkStyle.apps.workstyle.templatetags import wsfilters
  73. 73. > emacs Porject/apps/workstyle/task.py from WorkStyle.apps.workstyle.templatetags import wsfilters > emacs Project/apps/workstyle/templates/workstyle/TaskList.html {% load wsfilters %} {{ task.task|truncatelines:3 }}
  74. 74. Test pyunit simon.bofh.ms
  75. 75. Django Milestone 0.92 Magic 1.00
  76. 76. www.everes.net

×