view wsgraph/web.py @ 4:c7170cab1184

more RESTful stubbing
author Jeff Hammel <jhammel@mozilla.com>
date Sun, 09 Dec 2012 20:10:07 -0800
parents 42f484880808
children 9d5a8c90c482
line wrap: on
line source

#!/usr/bin/env python

"""
web handler for WSGraph
"""

import json
from webob import Request, Response, exc

GRAPH = 0
NODE = 1
EDGE = 2

def JSONFormatter(**kwargs):
    return json.dumps(kwargs, sort_keys=True)

def JSONGraphFormatter(graph):
    return json.dumps({'nodes': graph.nodes(),
                       'edges': graph.edges()},
                      sort_keys=True)

class Dispatcher(object):

    def __init__(self, graph,
                 graph_formatters=None, # TODO
                 node_formatters=None, # TODO
                 edge_formatters=None, # TODO
                 require_auth=False):
        self.graph = graph
        self.require_auth = require_auth
        self.formatters = {0: JSONGraphFormatter,
                           1: JSONFormatter,
                           2: JSONFormatter}

        self.methods = dict([(i, getattr(self, i))
                             for i in dir(self)
                             if i.isupper()])

    def __call__(self, environ, start_response):
        request = Request(environ)
        method = self.methods.get(request.method)
        if method is None:
            return exc.HTTPMethodNotAllowed()(environ, start_response)
        response = method(request)
        return response(environ, start_response)

    @staticmethod
    def path_segments(request):
        import pdb; pdb.set_trace()

    # HTTP methods

    def GET(self, request):
        """
        respond to a GET request

        Formatters are keyed off of

        formatters = {0: {
        }

        A graph formatter takes the following arguments:

          def sample_graph_formatter(graph, request):

        API:

        ?format=<format>

        """

        segments = self.path_segments(request)
        if len(segments) not in (0,1,2):
            return exc.HTTPNotFound()

        # formatter
        formatter = self.formatters[len(segments)]
        return Response(content_type='text/plain',
                        body="WSGraph")

    def POST(self, request):
        """
        respond to a POST request

        API:

        ?update :
        """

        return exc.HTTPSeeOther(location='/') # TODO: /path/to/self

    def HEAD(self, request):
        """respond to a HEAD request"""
        raise NotImplementedError

    def OPTIONS(self, request):
        return Response() # TODO: Allow=', '.join(self.methods); Content-Length=0

if __name__ == '__main__':

    ### example web server

    # imports
    from wsgiref import simple_server
    from model import MemoryCache
    from optparse import OptionParser

    # parse command line options
    parser = OptionParser()
    parser.add_option('-p', '--port', type='int', default=8080,
                      help="port to serve on")
    options, args = parser.parse_args()

    # example model
    graph = MemoryCache()

    # WSGI app
    app = Dispatcher(graph=graph)
    server = simple_server.make_server(host='0.0.0.0', port=options.port, app=app)
    print 'http://localhost:%s/' % options.port
    server.serve_forever()