DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. What WSGI is

What WSGI is

Giorgio Sironi user avatar by
Giorgio Sironi
·
Feb. 07, 12 · Interview
Like (0)
Save
Tweet
Share
7.82K Views

Join the DZone community and get the full member experience.

Join For Free
WSGI (Web Server Gateway Interface) is the standard for interfacing Python web applications with web servers. One of the Python syntax mantras is there should be one and preferably only one way to do it - and WSGI has become the way for responding to HTTP requests in Python code.

What about mod_python?

Unlike mod_python, WSGI is server independent: mod_wsgi implements the standard specification for Apache, but you can choose other modules for other servers, or even servers that just implement WSGI if you only need to run Python web applications.

Thus conforming to WSGI allows you to defer the decision of which hosting service or server to deploy to, without adding the complexity of an additional abstraction layer.
mod_wsgi is also considered lightweight with respect to mod_python, so even under Apache there are few clear reasons for preferring mod_python today.

On the other side of the fence, the Python code, all Python frameworks provide support for WSGI, even Zope starting from its 3.x release.

mod_python is also not developed anymore, and there will be no new releases since its move in the Apache Attic. If you're an user of mod_python, the move does not impact you as mod_python won't disappear in the next years (given Cobol is still around;) but WSGI is the standard choice for every new web application.

Installation

WSGI is not a library, but a specification: so there are only implementations of WSGI wrappers that interface a web server with your Python code.

For example, if you are on Ubuntu (or Debian derivatives) and you want to serve an application in Apache, the libapache2-mod-wsgi package will install and enable mod_wsgi. It will be our reference implementation for the rest of this article.

An Hello World can't be missing here

WSGI defines a single entry point for an application: a callable named *application*, accepting two parameters.

  • environment will contain GET variables and other CGI parameters.
  • start_response will be a function to call when you want to start sending a response. It accepts an HTTP status code and a list of headers (represented as 2-tuples).

The application callable should return a list of strings that have to be concatenated to build the response.

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]

This Python code is portable across any web server where there is a module binding for OSGI.

The configuration varies instead depending on your server. For example, this is the minimal Apache configuration you can put in a VirtualHost section, supposing application.py contains the code listed above.

WSGIScriptAlias /hello /var/www/wsgi/application.py

There are many more directives available for mod_wsgi:

  • WSGIPythonPath specifies any directories where to search Python modules.
  • WSGICallableObject overrides the callable name for the front controller function. When not specified, it remains "application".

 

Frameworks: Django

If you're using a Python framework, it's likely that you can already conform to WSGI using code provided by the framework itself.

For example, the Django WSGI binding imports a bunch of libraries and provides an application callable by grabbing Django's predefined one instead of defining it anew:

import os, sys
sys.path.append('/usr/local/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()

Django implements the callable as an object with __call__() instead of a function. The two options are totally equivalent, though:

class WSGIHandler(base.BaseHandler):
    initLock = Lock()
    request_class = WSGIRequest

    def __call__(self, environ, start_response):
        ...
        start_response(status, response_headers)
        return response

 

Google App Engine

Google App Engine also tells you to define a WSGI callable, and it provides it via its own web framework, webapp2 (or webapp for the older versions of Python); not that you cannot run Django on it. However, generating a front end for a list of handlers is the simplest way to run an application built on webapp2:

import webapp2

app = webapp2.WSGIApplication([('/', MainPage),
                               ('/newentry', NewEntry),
                               ('/editentry', EditEntry),
                               ('/deleteentry', DeleteEntry),
                              ],
                              debug=True)

The MainPage and the other handler classes are defined according to webapp2 contracts, but the front end is still WSGI. In fact, thanks to this standard webapp2 is not even tied to Google App Engine: you can take your application elsewhere without changing the code above.

Conclusion

A framework will probably hide from you a bit of the complexity inherent in WSGI callables; yet HTTP is the lowest common denominator between web applications and it's handy to know how the server and the framework communicate under the covers, especially when things go awry and you have to find out where the issue is.

Moreover, deploying a web application always pass through choosing a server with WSGI support, enabling it and adding the configuration necessary for it to find the callable and the relevant infrastructure (such as all your Python modules).

application Python (language) Web Service

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Beginner’s Guide To Styling CSS Forms
  • Demystifying Multi-Cloud Integration
  • OpenVPN With Radius and Multi-Factor Authentication
  • Strategies for Kubernetes Cluster Administrators: Understanding Pod Scheduling

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: