SlideShare a Scribd company logo
GETTING
 STARTED
   WITH
MOD_WSGI
Graham Dumpleton
   PyCon Australia
     June 2010
WHAT IS WSGI?
• Specification
            for an interface between web servers and
 Python web applications or frameworks.

• Intended to promote web application portability across a
 variety of web servers.

• PEP   333 - http://www.python.org/dev/peps/pep-0333

• More   Information - http://www.wsgi.org
WHAT IS MOD_WSGI?

• An Apache module to support hosting WSGI applications in
 conjunction with the Apache web server.

• Interceptsrequests to designated URLs and passes requests
 off to the WSGI application specified in the target WSGI script
 file that the URL maps to.
HELLO WORLD
def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]
MAPPING A URL

• Mapping WSGI   application at root of web server.
 WSGIScriptAlias / /home/grumpy/example-1/hello.wsgi


• Mapping WSGI   application at sub URL of web server.
 WSGIScriptAlias /suburl /home/grumpy/example-1/hello.wsgi
FORBIDDEN




client denied by server configuration: /home/grumpy/example-1/hello.wsgi
DENY FROM ALL

• By   default Apache denies access to everything.
 <Directory />
 Order deny,allow
 Deny from all
 </Directory>


• Thus   we need to open up access to our script.
 <Directory /home/grumpy/example-1>
 Order deny,allow
 Allow from all
 </Directory>
FORBIDDEN




(13)Permission denied: access to / denied
DRWXR-X---
• Apache    server child processes runs as a special user.

• The Apacheuser must be able to search directories down to
 where the WSGI script file is located.

• User
     account home directories often have permissions of
 drwxr-x--- and access is thereby restricted.

• Make   directories accessable to others.
 chmod o+rx /home/grumpy


• Better   still, don’t put WSGI script files under home directories.
INTERNAL SERVER ERROR




        (13)Permission denied: mod_wsgi (pid=666, process='',
application='tests.example.com|'): Call to fopen() failed for '/home/
                    grumpy/example-1/echo.wsgi'.
-RW-R-----

• Apache   server child processes runs as a special user.

• The Apache   user must be able to read the WSGI script file.

•A user account umask of 0007 will result in files being created
 with permissions of -rw-r----- and access is thereby restricted.

• Make   files readable to others.
 chmod o+r /home/grumpy/example-1/hello.wsgi
SUCCESS
DJANGO APPLICATION
• Install   Django.

• Create     an empty project.
  mkdir /home/grumpy/example-2
  cd /home/grumpy/example-2

  django-admin.py startproject mysite


• Run   the Django development server.
  python mysite/manage.py runserver
SUCCESS
DJANGO WSGI SCRIPT

import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
DJANGO APACHE CONFIG

WSGIScriptAlias / /home/grumpy/example-2/apache/mysite.wsgi

<Directory /home/grumpy/example-2/apache>
Order deny,allow
Allow from all
</Directory>
INTERNAL SERVER ERROR




 raise ImportError("Could not import settings '%s' (Is it on sys.path?
    Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e))
  ImportError: Could not import settings 'mysite.settings' (Is it on
sys.path? Does it have syntax errors?): No module named mysite.settings
SYS.PATH
• Pythonmodules/packages are not imported relative to current
 working directory.

• Python modules/packages are not imported relative to the
 directory containing the WSGI script file.

• The  PYTHONPATH of the user who owns the WSGI script
 file is not consulted.

• Therefore
          must explicitly designate directories to search for
 Python modules/packages.
SYS.PATH.INSERT()

import os
import sys

root = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, root)

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
SUCCESS
VIRTUAL ENVIRONMENT

• Create     and activate virtual environment
  cd /home/grumpy/example-2
  virtualenv --no-site-packages environ
  source environ/bin/activate


• Install   Django and other required packages.
  easy_install Django
SUCCESS
INTERNAL SERVER ERROR




 ImportError: No module named django.core.handlers.wsgi
SYS.PATH.INSERT()

import os
import sys

root = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, root)

packages = os.path.join(root,
    'environ/lib/python2.6/site-packages'
sys.path.insert(0, packages)

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
SITE.ADDSITEDIR()
import os
import sys
import site

root = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, root)

packages = os.path.join(root,
    'environ/lib/python2.6/site-packages'
site.addsitedir(packages)

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
ACTIVATE THIS
import os
import sys

root = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, root)

activate_this = os.path.join(root,
    'environ/bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
SITE-PACKAGES
• Using sys.path.insert() allows directory to be placed first,
 but .pth files do not get processed.

• Using
      site.addsitedir() results in .pth files being processed, but
 new directories get placed last.

• Using activate_this.py results in .pth files being processed and
 sys.path reordered such that new directories get placed first.

• Value
      of sys.prefix is however altered by activate_this.py and
 no certainty over whether this may cause later issues.
SUCCESS
DJANGO ADMIN PAGES

• Add ‘django.contrib.admin’ to   INSTALLED_APPS in the file
 ‘mysite/settings.py’.

• Add  (r'^admin/', include(admin.site.urls)) to 'urlpatterns’ in the
 file ‘mysite/urls.py’.

• Configure ‘DATABASES’ in     the file ‘mysite/settings.py’.

• Synchronise   database model.
 python mysite/manage.py syncdb
SUCCESS
NOT FOUND
STATIC MEDIA FILES

• Django’s
         static media files are only served automatically by the
 Django development server and not when using Django
 WSGIHandler object.

• Mustmanually map any static media files to appropriate sub
 URL in Apache.
ALLOW FROM ALL
WSGIScriptAlias / /home/grumpy/example-2/apache/mysite.wsgi

<Directory /home/grumpy/example-2/apache>
Order deny,allow
Allow from all
</Directory>

Alias /media/ /home/grumpy/example-2/media/

<Directory /home/grumpy/example-2/media/>
Order deny,allow
Allow from all
</Directory>
SUCCESS
SUMMARY OF MAIN POINTS

• Need   to tell Apache what resources it should allow access to.

• Apache   user needs access to WSGI script file/directory.

• Application   user needs read access to source code.

• Application   user needs to be able to write to data directories.

• Python   needs to know where to search for modules/packages.
ONLINE RESOURCES
• The   mod_wsgi documentation.

 http://www.modwsgi.org

 http://code.google.com/p/modwsgi/wiki/WhereToGetHelp
 http://code.google.com/p/modwsgi/wiki/VirtualEnvironments
 http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode

• Personal   blog posts.

 http://blog.dscpl.com.au

More Related Content

PDF
JavaFX Overview
PDF
Kubernetes & helm 활용
PPTX
TypeScript intro
PDF
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
PPT
Inheritance C#
PDF
Understanding react hooks
PPTX
JavaFX Presentation
PPTX
JavaFX Overview
Kubernetes & helm 활용
TypeScript intro
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Inheritance C#
Understanding react hooks
JavaFX Presentation

What's hot (20)

PDF
Git real slides
PPTX
GitHub Basics - Derek Bable
PPT
Access Protection
PPT
Visual Studio IDE
PPTX
Java packages
PPTX
Git commands
PDF
Vue, vue router, vuex
PDF
A Practical Introduction to git
PDF
Basics of React Hooks.pptx.pdf
PPTX
Java socket programming
PPTX
Web services - A Practical Approach
PPTX
Docker advance topic
PDF
Angular - Chapter 5 - Directives
PPTX
Introducing type script
PDF
Git & Github for beginners
PDF
AngularJS for Beginners
PDF
Intro to Git and GitHub
PPTX
Getting started with typescript
PDF
Building .NET Microservices
Git real slides
GitHub Basics - Derek Bable
Access Protection
Visual Studio IDE
Java packages
Git commands
Vue, vue router, vuex
A Practical Introduction to git
Basics of React Hooks.pptx.pdf
Java socket programming
Web services - A Practical Approach
Docker advance topic
Angular - Chapter 5 - Directives
Introducing type script
Git & Github for beginners
AngularJS for Beginners
Intro to Git and GitHub
Getting started with typescript
Building .NET Microservices
Ad

Viewers also liked (6)

PDF
PyCon NZ 2013 - Advanced Methods For Creating Decorators
PDF
PyCon AU 2015 - Using benchmarks to understand how wsgi servers work
PDF
PyCon HK 2015 - Monitoring the performance of python web applications
PDF
Python WSGI introduction
PPT
A Brief Introduce to WSGI
PDF
Data analytics in the cloud with Jupyter notebooks.
PyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon AU 2015 - Using benchmarks to understand how wsgi servers work
PyCon HK 2015 - Monitoring the performance of python web applications
Python WSGI introduction
A Brief Introduce to WSGI
Data analytics in the cloud with Jupyter notebooks.
Ad

Similar to PyCon AU 2010 - Getting Started With Apache/mod_wsgi. (20)

KEY
Deploying
PDF
Pyramid Deployment and Maintenance
PDF
“warpdrive”, making Python web application deployment magically easy.
PPTX
PDF
Deploying Django with Ansible
PPT
Python Deployment with Fabric
PDF
WPDay Bologna 2013
PDF
Oracle API Gateway Installation
PDF
Manage WordPress with Awesome using wp cli
PDF
Provisioning with Puppet
PPTX
Django Architecture Introduction
PPTX
Deployment with Fabric
PDF
Zero Downtime Deployment with Ansible
PDF
Dev ninja -> vagrant + virtualbox + chef-solo + git + ec2
PDF
[Devconf.cz][2017] Understanding OpenShift Security Context Constraints
PDF
WordCamp Vancouver 2012 - Manage WordPress with Awesome using wp-cli
PDF
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
PPTX
Introduction to Client Side Dev in SharePoint Workshop
PPTX
Vagrant WordCamp Hamilton
PDF
BP-6 Repository Customization Best Practices
Deploying
Pyramid Deployment and Maintenance
“warpdrive”, making Python web application deployment magically easy.
Deploying Django with Ansible
Python Deployment with Fabric
WPDay Bologna 2013
Oracle API Gateway Installation
Manage WordPress with Awesome using wp cli
Provisioning with Puppet
Django Architecture Introduction
Deployment with Fabric
Zero Downtime Deployment with Ansible
Dev ninja -> vagrant + virtualbox + chef-solo + git + ec2
[Devconf.cz][2017] Understanding OpenShift Security Context Constraints
WordCamp Vancouver 2012 - Manage WordPress with Awesome using wp-cli
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
Introduction to Client Side Dev in SharePoint Workshop
Vagrant WordCamp Hamilton
BP-6 Repository Customization Best Practices

More from Graham Dumpleton (10)

PDF
Implementing a decorator for thread synchronisation.
PDF
Not Tom Eastman
PDF
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
PDF
OpenShift, Docker, Kubernetes: The next generation of PaaS
PDF
Automated Image Builds in OpenShift and Kubernetes
PDF
PyCon US 2013 Making Apache suck less for hosting Python web applications
KEY
PyCon US 2012 - State of WSGI 2
KEY
PyCon AU 2012 - Debugging Live Python Web Applications
KEY
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
KEY
DjangoCon US 2011 - Monkeying around at New Relic
Implementing a decorator for thread synchronisation.
Not Tom Eastman
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
OpenShift, Docker, Kubernetes: The next generation of PaaS
Automated Image Builds in OpenShift and Kubernetes
PyCon US 2013 Making Apache suck less for hosting Python web applications
PyCon US 2012 - State of WSGI 2
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
DjangoCon US 2011 - Monkeying around at New Relic

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Cloud computing and distributed systems.
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Machine learning based COVID-19 study performance prediction
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Modernizing your data center with Dell and AMD
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Mobile App Security Testing_ A Comprehensive Guide.pdf
Big Data Technologies - Introduction.pptx
Cloud computing and distributed systems.
NewMind AI Monthly Chronicles - July 2025
Encapsulation_ Review paper, used for researhc scholars
Machine learning based COVID-19 study performance prediction
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Spectral efficient network and resource selection model in 5G networks
“AI and Expert System Decision Support & Business Intelligence Systems”
Digital-Transformation-Roadmap-for-Companies.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Advanced methodologies resolving dimensionality complications for autism neur...
Modernizing your data center with Dell and AMD
Dropbox Q2 2025 Financial Results & Investor Presentation
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Chapter 3 Spatial Domain Image Processing.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx

PyCon AU 2010 - Getting Started With Apache/mod_wsgi.

  • 1. GETTING STARTED WITH MOD_WSGI Graham Dumpleton PyCon Australia June 2010
  • 2. WHAT IS WSGI? • Specification for an interface between web servers and Python web applications or frameworks. • Intended to promote web application portability across a variety of web servers. • PEP 333 - http://www.python.org/dev/peps/pep-0333 • More Information - http://www.wsgi.org
  • 3. WHAT IS MOD_WSGI? • An Apache module to support hosting WSGI applications in conjunction with the Apache web server. • Interceptsrequests to designated URLs and passes requests off to the WSGI application specified in the target WSGI script file that the URL maps to.
  • 4. HELLO WORLD def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output]
  • 5. MAPPING A URL • Mapping WSGI application at root of web server. WSGIScriptAlias / /home/grumpy/example-1/hello.wsgi • Mapping WSGI application at sub URL of web server. WSGIScriptAlias /suburl /home/grumpy/example-1/hello.wsgi
  • 6. FORBIDDEN client denied by server configuration: /home/grumpy/example-1/hello.wsgi
  • 7. DENY FROM ALL • By default Apache denies access to everything. <Directory /> Order deny,allow Deny from all </Directory> • Thus we need to open up access to our script. <Directory /home/grumpy/example-1> Order deny,allow Allow from all </Directory>
  • 9. DRWXR-X--- • Apache server child processes runs as a special user. • The Apacheuser must be able to search directories down to where the WSGI script file is located. • User account home directories often have permissions of drwxr-x--- and access is thereby restricted. • Make directories accessable to others. chmod o+rx /home/grumpy • Better still, don’t put WSGI script files under home directories.
  • 10. INTERNAL SERVER ERROR (13)Permission denied: mod_wsgi (pid=666, process='', application='tests.example.com|'): Call to fopen() failed for '/home/ grumpy/example-1/echo.wsgi'.
  • 11. -RW-R----- • Apache server child processes runs as a special user. • The Apache user must be able to read the WSGI script file. •A user account umask of 0007 will result in files being created with permissions of -rw-r----- and access is thereby restricted. • Make files readable to others. chmod o+r /home/grumpy/example-1/hello.wsgi
  • 13. DJANGO APPLICATION • Install Django. • Create an empty project. mkdir /home/grumpy/example-2 cd /home/grumpy/example-2 django-admin.py startproject mysite • Run the Django development server. python mysite/manage.py runserver
  • 15. DJANGO WSGI SCRIPT import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
  • 16. DJANGO APACHE CONFIG WSGIScriptAlias / /home/grumpy/example-2/apache/mysite.wsgi <Directory /home/grumpy/example-2/apache> Order deny,allow Allow from all </Directory>
  • 17. INTERNAL SERVER ERROR raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'mysite.settings' (Is it on sys.path? Does it have syntax errors?): No module named mysite.settings
  • 18. SYS.PATH • Pythonmodules/packages are not imported relative to current working directory. • Python modules/packages are not imported relative to the directory containing the WSGI script file. • The PYTHONPATH of the user who owns the WSGI script file is not consulted. • Therefore must explicitly designate directories to search for Python modules/packages.
  • 19. SYS.PATH.INSERT() import os import sys root = os.path.join(os.path.dirname(__file__), '..') sys.path.insert(0, root) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
  • 21. VIRTUAL ENVIRONMENT • Create and activate virtual environment cd /home/grumpy/example-2 virtualenv --no-site-packages environ source environ/bin/activate • Install Django and other required packages. easy_install Django
  • 23. INTERNAL SERVER ERROR ImportError: No module named django.core.handlers.wsgi
  • 24. SYS.PATH.INSERT() import os import sys root = os.path.join(os.path.dirname(__file__), '..') sys.path.insert(0, root) packages = os.path.join(root, 'environ/lib/python2.6/site-packages' sys.path.insert(0, packages) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
  • 25. SITE.ADDSITEDIR() import os import sys import site root = os.path.join(os.path.dirname(__file__), '..') sys.path.insert(0, root) packages = os.path.join(root, 'environ/lib/python2.6/site-packages' site.addsitedir(packages) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
  • 26. ACTIVATE THIS import os import sys root = os.path.join(os.path.dirname(__file__), '..') sys.path.insert(0, root) activate_this = os.path.join(root, 'environ/bin/activate_this.py') execfile(activate_this, dict(__file__=activate_this)) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
  • 27. SITE-PACKAGES • Using sys.path.insert() allows directory to be placed first, but .pth files do not get processed. • Using site.addsitedir() results in .pth files being processed, but new directories get placed last. • Using activate_this.py results in .pth files being processed and sys.path reordered such that new directories get placed first. • Value of sys.prefix is however altered by activate_this.py and no certainty over whether this may cause later issues.
  • 29. DJANGO ADMIN PAGES • Add ‘django.contrib.admin’ to INSTALLED_APPS in the file ‘mysite/settings.py’. • Add (r'^admin/', include(admin.site.urls)) to 'urlpatterns’ in the file ‘mysite/urls.py’. • Configure ‘DATABASES’ in the file ‘mysite/settings.py’. • Synchronise database model. python mysite/manage.py syncdb
  • 32. STATIC MEDIA FILES • Django’s static media files are only served automatically by the Django development server and not when using Django WSGIHandler object. • Mustmanually map any static media files to appropriate sub URL in Apache.
  • 33. ALLOW FROM ALL WSGIScriptAlias / /home/grumpy/example-2/apache/mysite.wsgi <Directory /home/grumpy/example-2/apache> Order deny,allow Allow from all </Directory> Alias /media/ /home/grumpy/example-2/media/ <Directory /home/grumpy/example-2/media/> Order deny,allow Allow from all </Directory>
  • 35. SUMMARY OF MAIN POINTS • Need to tell Apache what resources it should allow access to. • Apache user needs access to WSGI script file/directory. • Application user needs read access to source code. • Application user needs to be able to write to data directories. • Python needs to know where to search for modules/packages.
  • 36. ONLINE RESOURCES • The mod_wsgi documentation. http://www.modwsgi.org http://code.google.com/p/modwsgi/wiki/WhereToGetHelp http://code.google.com/p/modwsgi/wiki/VirtualEnvironments http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode • Personal blog posts. http://blog.dscpl.com.au

Editor's Notes