WSGI Beispiele

Sockets, TCP/IP, (XML-)RPC und ähnliche Themen gehören in dieses Forum
Antworten
mitsuhiko
User
Beiträge: 1790
Registriert: Donnerstag 28. Oktober 2004, 16:33
Wohnort: Graz, Steiermark - Österreich
Kontaktdaten:

Was haltet ihr von eine WSGI Beispiele im Wiki, die ohne Colubrid und co auskommen? Nur mal so als "so funktioniert wsgi"

hier wäre eines, dass imho einfach zu verstehen ist:

Code: Alles auswählen

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


class Application(object):
    urls = {}
    charset = 'utf-8'

    def __call__(self, environ, start_response):
        path = environ.get('PATH_INFO', '').strip('/')
        headers = [('Content-Type', 'text/html; charset=%s' % self.charset)]
        status = '200 OK'
        for regex, handler in self.urls.iteritems():
            matchobj = regex.search(path)
            if not matchobj is None:
                response = handler(environ, *matchobj.groups())
                if isinstance(response, tuple):
                    if len(response) == 3:
                        response, headers, status = response
                    else:
                        response, headers = response
                if isinstance(response, unicode):
                    response = [response.decode(self.charset)]
                elif isinstance(response, str):
                    response = [response]
                start_response(status, headers)
                return iter(response)
        # error page
        start_response('404 NOT FOUND', headers)
        return ['Page Not Found']
    

def export(regex):
    def wrapped(f):
        Application.urls[re.compile(regex)] = f
        return f
    return wrapped


@export('^$')
def index(environ):
    return 'Hello from the Index'

@export('^downloads$')
def downloads(environ):
    return 'Hello from the Downloads'


app = Application()

if __name__ == '__main__':
    from paste.httpserver import serve
    serve(app)
TUFKAB – the user formerly known as blackbird
Antworten