wsgi tutorial

Introduction

What WSGI¹ is not: a server, a python module, a framework, an API or any kind of software. What it is: an interface specification by which server and application communicate. Both server and application interface sides are specified. It does not exist anywhere else other than as words in thePEP 3333. If an application (or framework or toolkit) is written to the WSGI spec then it will run on any server written to that spec.

WSGI applications (meaning WSGI compliant) can be stacked. Those in the middle of the stack are called middleware and must implement both sides of the WSGI interface, application and server. For the application in top of it it will behave as a server and for the application (or server) bellow as an application.

A WSGI server (meaning WSGI compliant) only receives the request from the client, pass it to the application and then send the response provided by the application to the client. It does nothing else. All the gory details must be supplied by the application or middleware.

It is not necessary to learn the WSGI spec to use frameworks or toolkits. To use middleware one must have a minimum understanding of how to stack them with the application or framework unless it is already integrated in the framework or the framework provides some kind of wrapper to integrate those that are not.

Python 2.5 and later comes with a WSGI server which will be used in this tutorial. In 2.4 and earlier it can beinstalled. For anything other than learning I strongly recommend Apache withmod_wsgi.

All the code in this tutorial is low level and has the sole purpose to be didactic by showing the WSGI specification at work. It is not meant for real use. For production code use toolkits, frameworks and middleware.

¹ Web Server Gateway Interface

Application Interface

The WSGI application interface is implemented as a callable object: a function, a method, a class or an instance with a __call__ method. That callable

  • must accept two positional parameters:

    • A dictionary containing CGI like variables; and
    • a callback function that will be used by the application to send HTTP status code/message and HTTP headers to the server.
  • and must return the response body to the server as strings wrapped in an iterable.

The application skeleton:

# This is our application object. It could have any name,
# except when using mod_wsgi where it must be "application"
def application( # It accepts two arguments:
      # environ points to a dictionary containing CGI like environment variables
      # which is filled by the server for each received request from the client
      environ,
      # start_response is a callback function supplied by the server
      # which will be used to send the HTTP status and headers to the server
      start_response):

   # build the response body possibly using the environ dictionary
   response_body = 'The request method was %s' % environ['REQUEST_METHOD']

   # HTTP response code and message
   status = '200 OK'

   # These are HTTP headers expected by the client.
   # They must be wrapped as a list of tupled pairs:
   # [(Header name, Header value)].
   response_headers = [('Content-Type', 'text/plain'),
                       ('Content-Length', str(len(response_body)))]

   # Send them to the server using the supplied function
   start_response(status, response_headers)

   # Return the response body.
   # Notice it is wrapped in a list although it could be any iterable.
   return [response_body]

This code will not run because it lacks the server instantiation step.

Environment dictionary

The environment dictionary will contain CGI like variables and will be populated by the server at each request from the client. This script will output the whole dictionary:

#! /usr/bin/env python

# Our tutorial's WSGI server
from wsgiref.simple_server import make_server

def application(environ, start_response):

   # Sorting and stringifying the environment key, value pairs
   response_body = ['%s: %s' % (key, value)
                    for key, value in sorted(environ.items())]
   response_body = '\n'.join(response_body)

   status = '200 OK'
   response_headers = [('Content-Type', 'text/plain'),
                  ('Content-Length', str(len(response_body)))]
   start_response(status, response_headers)

   return [response_body]

# Instantiate the WSGI server.
# It will receive the request, pass it to the application
# and send the application's response to the client
httpd = make_server(
   'localhost', # The host name.
   8051, # A port number where to wait for the request.
   application # Our application object name, in this case a function.
   )

# Wait for a single request, serve it and quit.
httpd.handle_request()

To run this script save it asenvironment.py, open the terminal, navigate to the directory where it was saved and typepython environment.py at the command line.

If in Windows it is necessary first to add the path topython.exe to the system environment variablePath. By the way if you can use Linux in instead of Windows then do it. It will save some pain.

Now go to the browser and type at the address bar:

http://localhost:8051/

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值