2013年3月12日火曜日

python httpサーバ(wsgi編)

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from wsgiref.simple_server import make_server, WSGIRequestHandler
import urlparse


html_index = '<html><body>hello</body></html>'


def appl(environ,start_response):

  path = environ['PATH_INFO']
  method = environ['REQUEST_METHOD']

  if method=='GET':
    query = dict(urlparse.parse_qsl(environ.get('QUERY_STRING','')))

  if method=='POST':
    ro = environ['wsgi.input']
    length = int(environ.get('CONTENT_LENGTH', 0))
    query = dict(urlparse.parse_qsl(ro.read(length)))

  if path=='/' and method=='GET':
    response_headers = [('Content-Type', 'text/html'),
      ('Content-Length', str(len(html_index)))]
    start_response('200 OK', response_headers)
    return [html_index]

  if path=='/' and method=='POST':
    start_responce('303 See Other', [('Location', '/')])
    return []

  start_response('404 Not Found', [])
  return []


#  DNS逆名前解決しない
class myHandler(WSGIRequestHandler):
  def address_string(self):
    return self.client_address[0]


httpd = make_server('0.0.0.0', 80, appl, handler_class=myHandler)
httpd.serve_forever()

0 件のコメント:

コメントを投稿