Django Deployment & Tips 2010. 6. 7 daybreaker. We have covered… ▶ Django Basics  Concept of MVC  Templates  Models  Admin Sites  Forms  Users (authentication)

Slides:



Advertisements
Similar presentations
Overview and Demonstration of declarative workflows in SharePoint using Microsoft SharePoint Designer 2007 Kevin Hughes MCT, MCITP, MCSA, MCTS, MCP, Network+,
Advertisements

OCLC Online Computer Library Center CONTENTdm Developers Meeting ALA Midwinter Meeting Seattle, WA January 19 th, 2007 Claire Cocco, Product Manager Joe.
DT211/3 Internet Application Development Active Server Pages & IIS Web server.
DEV392: Extending SharePoint Products And Technologies Through Web Parts And ASP.NET Clint Covington, Program Manager Data And Developer Services - Office.
Copyright 2004 Monash University IMS5401 Web-based Systems Development Topic 2: Elements of the Web (g) Interactivity.
28/1/2001 Seminar in Databases in the Internet Environment Introduction to J ava S erver P ages technology by Naomi Chen.
1 CS6320 – Why Servlets? L. Grewe 2 What is a Servlet? Servlets are Java programs that can be run dynamically from a Web Server Servlets are Java programs.
Peoplesoft: Building and Consuming Web Services
LHCbPR V2 Sasha Mazurov, Amine Ben Hammou, Ben Couturier 5th LHCb Computing Workshop
Web Application Architecture: multi-tier (2-tier, 3-tier) & mvc
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
Linux Operations and Administration
Web Development Methodologies Yuan Wang(yw2326). Basic Concepts Browser/Server (B/S) Structure Keywords: Browser, Server Examples: Websites Client/Server.
DAT602 Database Application Development Lecture 15 Java Server Pages Part 1.
Virtual techdays INDIA │ august 2010 IIS 7/7.5 Tips & Tricks Jaskirat Singh │ Technical Lead [IIS|Asp.Net team], Microsoft.
CEDROM-SNi’s DITA- based Project From Analysis to Delivery By France Baril Documentation Architect.
Sys Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 15: PHP Introduction.
Dataface API Essentials Steve Hannah Web Lite Solutions Corp.
Apache Server The Apache Server Apache is a WWW server that implements the HTTP protocol. Apache runs as a daemon. This means that it is a resident.
1 Web Server Concepts Dr. Awad Khalil Computer Science Department AUC.
건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs.
Chapter 33 CGI Technology for Dynamic Web Documents There are two alternative forms of retrieving web documents. Instead of retrieving static HTML documents,
SIMPLE ROUTER The slide made by Salim Malakouti. Next we will create the Router  What do I we mean by a router?  Routers work similar to a map. It receives.
5 Chapter Five Web Servers. 5 Chapter Objectives Learn about the Microsoft Personal Web Server Software Learn how to improve Web site performance Learn.
Inventory:OCSNG + GLPI Monitoring: Zenoss 3
Putting What We Learned Into Context – WSGI and Web Frameworks A290/A590, Fall /16/2014.
from SimpleHTTPServer import SimpleHTTPRequestHandler import SocketServer httpd = SocketServer.TCPServer((‘’, 8000), SimpleHTTPRequestHandler) httpd.serve_forever()
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 21 - Web Servers (IIS, PWS and Apache) Outline 21.1 Introduction 21.2 HTTP Request Types 21.3.
1 Apache. 2 Module - Apache ♦ Overview This module focuses on configuring and customizing Apache web server. Apache is a commonly used Hypertext Transfer.
Ideas to Improve SharePoint Usage 4. What are these 4 Ideas? 1. 7 Steps to check SharePoint Health 2. Avoid common Deployment Mistakes 3. Analyze SharePoint.
Revolutionizing enterprise web development Searching with Solr.
The Web Architecture and ASP.NET. Slide 2 Review of the Web (1) It began with HTTP and HTML, which delivers static Web pages to browsers which would render.
10/13/2015 ©2006 Scott Miller, University of Victoria 1 Content Serving Static vs. Dynamic Content Web Servers Server Flow Control Rev. 2.0.
SQL Server User Group Meeting Reporting Services Tips & Tricks Presented by Jason Buck of Custom Business Solutions.
Chapter 6 Server-side Programming: Java Servlets
1 © Netskills Quality Internet Training, University of Newcastle HTML Forms © Netskills, Quality Internet Training, University of Newcastle Netskills is.
First Indico Workshop WEB FRAMEWORKS Adrian Mönnich May 2013 CERN.
Django 101 By: Jason Sumner. Django Overview Django was started in 2003, released under BSD in 2005, and the Django Software Foundation was established.
Google App Engine Data Store ae-10-datastore
1 Session 1: Introduction to PHP & MySQL iNET Academy Open Source Web Development.
Storing and Retrieving Data
 Registry itself is easy and straightforward in implementation  The objects of registry are actually complicated to store and manage  Objects of Registry.
Greenstone Internals How to Build a Digital Library Ian H. Witten and David Bainbridge.
Free Powerpoint Templates Page 1 Free Powerpoint Templates Users and Documents.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
MVC WITH CODEIGNITER Presented By Bhanu Priya.
WEB SERVER SOFTWARE FEATURE SETS
Threads. Readings r Silberschatz et al : Chapter 4.
(ITI310) By Eng. BASSEM ALSAID SESSIONS 10: Internet Information Services (IIS)
NMD202 Web Scripting Week2. Web site
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
APACHE STRUTS ASHISH SINGH TOMAR ast2124. OUTLINE Introduction The Model-View-Controller Design Pattern Struts’ implementation of the MVC Pattern Additional.
Ruby on Rails. Web Framework for Ruby Designed to make it easier to develop, deploy, and maintain web applications Design with Model-View-Controller –almost.
Introduction to ASP.NET development. Background ASP released in 1996 ASP supported for a minimum 10 years from Windows 8 release ASP.Net 1.0 released.
Modern Development Technologies in SharePoint SHAREPOINT SATURDAY OMAHA APRIL, 2016.
The Django Web Application Framework zhixiong.hong
How to use Drupal Awdhesh Kumar (Team Leader) Presentation Topic.
z/Ware 2.0 Technical Overview
Chapter 2: System Structures
PHP Training at GoLogica in Bangalore
PHP / MySQL Introduction
Development and Deployment with WSGI in Django
MapServer In its most basic form, MapServer is a CGI program that sits inactive on your Web server. When a request is sent to MapServer, it uses.
Chapter 27 WWW and HTTP.
Controllers.
Nate Nelson I*LEVEL, Inc.
Google App Engine Ying Zou 01/24/2016.
Lecture 21 More On Django.
Presentation transcript:

Django Deployment & Tips daybreaker

We have covered… ▶ Django Basics  Concept of MVC  Templates  Models  Admin Sites  Forms  Users (authentication) ▶ Thanks to battery…

Today’s Contents ▶ Deployment: mod_python & WSGI ▶ Tips: More Convenient Development ▶ Tips: More Elegant Structure ▶ Tips: Faster Application

Deployment: mod_python ▶ mod_python  Your code runs in apache processes (like traditional PHP) Apache Process … mod_python Your Django Code Apache Process mod_python Your Django Code Apache Process mod_python Your Django Code Directly handles HTTP requests…

Deployment: mod_python ▶ Apache Configuration  django.root specifies a global URL prefix for your site. DocumentRoot /projects/mysite/static/ SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root / PythonDebug On PythonPath "['/projects/'] + sys.path" SetHandler None DocumentRoot /projects/mysite/static/ SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root / PythonDebug On PythonPath "['/projects/'] + sys.path" SetHandler None

Deployment: WSGI ▶ WSGI (or FastCGI)  Your code runs in separated Python daemon processes via IPC.  More suitable for contemporary multi- processor systems Apache Process Python Process Your Django Code Python Process Your Django Code Daemon pool controlled by Apache NOTE: Lighttpd can be used instead of Apache. mod_wsgi Apache Process mod_wsgi Apache Process mod_wsgi

Deployment: WSGI ▶ Differences to traditional CGI  It reuses daemon processes, not launching them every time.  Permissions can be separated for better security. ▶ WSGI is the de-facto standard web application interface for Python.  FastCGI can also be used. (Modern PHP applications use it.)

Deployment: WSGI ▶ Apache Configuration (with mod_wsgi enabled) ▶ WSGI Handler Script WSGIDaemonProcess mysite processes=2 threads=15 user=daybreaker group=www-data WSGIProcessGroup mysite WSGIScriptAlias / /projects/mysite/django.wsgi WSGIDaemonProcess mysite processes=2 threads=15 user=daybreaker group=www-data WSGIProcessGroup mysite WSGIScriptAlias / /projects/mysite/django.wsgi #! /usr/bin/env python import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from django.core.handlers import wsgi application = wsgi.WSGIHandler() #! /usr/bin/env python import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from django.core.handlers import wsgi application = wsgi.WSGIHandler() optional

Deployment: WSGI ▶ Apache Configuration (extended)  We should set exception rules for static files. Alias /robots.txt /projects/mysite/static/robots.txt Alias /favicon.ico /projects/mysite/static/favicon.ico Alias /media/ /projects/mysite/static/media/ Order deny,allow Allow from all WSGIScriptAlias / /projects/mysite/django.wsgi Order allow,deny Allow from all Alias /robots.txt /projects/mysite/static/robots.txt Alias /favicon.ico /projects/mysite/static/favicon.ico Alias /media/ /projects/mysite/static/media/ Order deny,allow Allow from all WSGIScriptAlias / /projects/mysite/django.wsgi Order allow,deny Allow from all

You will know the tips or their necessity after some projects without this seminar. But it’s better to know best practices even before you understand why they are good.

More Convenient Develeopment ▶ Don’t hard-code MEDIA_ROOT, TEMPLATE_DIRS and static files in templates (Use MEDIA_URL) import os.path PROJECT_PATH = os.path.dirname(__file__) MEDIA_ROOT = os.path.join(PROJECT_PATH, 'static/media/') MEDIA_URL = '/media/' # may be other servers, eg. ' TEMPLATE_DIRS = ( os.path.join(PROJECT_PATH, 'templates'), ) import os.path PROJECT_PATH = os.path.dirname(__file__) MEDIA_ROOT = os.path.join(PROJECT_PATH, 'static/media/') MEDIA_URL = '/media/' # may be other servers, eg. ' TEMPLATE_DIRS = ( os.path.join(PROJECT_PATH, 'templates'), ) settings.py templates

More Convenient Develeopment ▶ RequestContext instead of Context  Automatically adds request, user template variables. from django.template import RequestContext def my_view(request): # do something return render_to_response('mytemplate.html', { … # some template variables }, context_instance=RequestContext(request)) from django.template import RequestContext def my_view(request): # do something return render_to_response('mytemplate.html', { … # some template variables }, context_instance=RequestContext(request)) In views

More Convenient Develeopment ▶ DEBUG = True/False depending on the server ▶ Or, settings_local.py for each server import socket if socket.gethostname() == 'productionserver.com': DEBUG = False else: DEBUG = True import socket if socket.gethostname() == 'productionserver.com': DEBUG = False else: DEBUG = True settings.py try: from settings_local import * except ImportError: pass try: from settings_local import * except ImportError: pass At the end of settings.py Then, create settings_local.py at the same directory.

More Convenient Develeopment ▶ Avoid using project name  Greatly increases reusability of apps (You don't have to fix all occurrences in all source files in an app when you try to use it in different projects.)  Manipulate PYTHON_PATH! (cont'd)

More Convenient Develeopment ▶ Avoid using project name from mysite.apps.myapp1.models import Model1 from mysite.apps.myapp2.models import Model2, Model3 from mysite.apps.myapp1.models import Model1 from mysite.apps.myapp2.models import Model2, Model3 In your apps #! /usr/bin/env python import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' current_path = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(current_path, 'apps')) from django.core.handlers import wsgi application = wsgi.WSGIHandler() #! /usr/bin/env python import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' current_path = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(current_path, 'apps')) from django.core.handlers import wsgi application = wsgi.WSGIHandler() WSGI Handler Script ※ This is for the case that apps are in 'apps' sub-package.

More Convenient Develeopment ▶ Load 3 rd -party templatetags automatically  No more manual {% load something %} in every template that uses it. from django import template template.add_to_builtins( 'someapp.templatetags.custom_tag_module' ) from django import template template.add_to_builtins( 'someapp.templatetags.custom_tag_module' ) At the end of settings.py

More Convenient Develeopment ▶ Django command extensions   Provides extra manage.py commands. shell_plus : automatic imports of models show_urls : lists all defined URLs …and many others!

More Convenient Development ▶ Testing multiple Django version on a single server #! /usr/bin/env python import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' sys.path = ['/path/to/secondary-django'] + sys.path from django.core.handlers import wsgi application = wsgi.WSGIHandler() #! /usr/bin/env python import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' sys.path = ['/path/to/secondary-django'] + sys.path from django.core.handlers import wsgi application = wsgi.WSGIHandler() WSGI Handler Script Note that the new path comes first.

More Elegant Structure ▶ Logic codes in models instead of views  For reusability and testability!  Views are coupled with HttpRequest & HttpResopnse, so they are dependent on their running environments. (It's tedious to provide simulation of them for unit-testing and granularity is too big.)  Models can be imported and used independently.

More Elegant Structure ▶ Use hierarchical urlpatterns  Even without additional urls.py files! labsite_urlpatterns = patterns('someapp.views', url(ur'^$', 'dashboard', name='dashboard'), url(ur'^join/$', 'new_join_request'), … ) urlpatterns = patterns('someapp.views', url(ur'^$', 'index', name='index'), url(ur'^browse/$', 'browse', name='browse'), … url(ur'^(?P [-a-zA-Z0-9]+)/', include(labsite_urlpatterns)), ) labsite_urlpatterns = patterns('someapp.views', url(ur'^$', 'dashboard', name='dashboard'), url(ur'^join/$', 'new_join_request'), … ) urlpatterns = patterns('someapp.views', url(ur'^$', 'index', name='index'), url(ur'^browse/$', 'browse', name='browse'), … url(ur'^(?P [-a-zA-Z0-9]+)/', include(labsite_urlpatterns)), ) someapp/urls.py

More Elegant Structure ▶ Use named URL pattern (with namespaces)  Reverse lookup improves reusability of your apps. labsite_urlpatterns = patterns('opencourselabs.labsite.views', … url(ur'^teams/(?P [0-9]+)/$', 'view_team_console', name='team-console'), ) urlpatterns = patterns('opencourselabs.labsite.views', … url(ur'^(?P [-a-zA-Z0-9]+)/', include(labsite_urlpatterns)), ) labsite_urlpatterns = patterns('opencourselabs.labsite.views', … url(ur'^teams/(?P [0-9]+)/$', 'view_team_console', name='team-console'), ) urlpatterns = patterns('opencourselabs.labsite.views', … url(ur'^(?P [-a-zA-Z0-9]+)/', include(labsite_urlpatterns)), ) {% for team in teams %} … {{team.name}} {% endfor %} {% for team in teams %} … {{team.name}} {% endfor %} urlpatterns = ('', … (ur'^lab/', include('opencourselabs.labsite.urls', namespace='labsite')), ) urlpatterns = ('', … (ur'^lab/', include('opencourselabs.labsite.urls', namespace='labsite')), ) labsite/urls.py urls.py In templates

Faster Application ▶ Caching, caching, caching.  Use cache for dynamic contents that does not need real-time updates but requires large computation.  Be aware of cache consistency!!!  Example: course search in OTL

Faster Application ▶ QuerySet.select_related()  Lazy evaluation sometimes makes excessive similar queries when accessing related objects from an object list.  Append select_related() at the end of queryset creation for complicated relational results.  Trades memory for performance.  OTL got vast performance improvements by this tip. MyObject.objects.filter(…).select_related()

Other Advanced Topics ▶ Refer battery's slides ▶ Advanced Models & QuerySets  Custom fields  Q() function for complicated filter expressions  Using signals for "ON DELETE", "ON UPDATE" ▶ Advanced Admin  Custom pages, custom forms and fields ▶ Making your own authentication backends  Using OpenID, oAuth, … ▶ Making your own management commands ./manage.py mycommand blah blah ▶ Using non-default template/db engine ▶ Caching – The secret how OTL survived. ▶ Internationalization (providing multilingual text) ▶ Tricks with Middleware – like global decorator

References ▶ Django 1.2 Documentation  Put this under your pillow! ▶ “Top 10 Tips to a New Django Developer” developer developer ▶ CCIU Open Course Labs  Read commercial-level codes and applications ▶ OTL