Beispiel #1
0
class Receiver(object):
    def handle_get_post(self, reqMethod):
        _inbox_url = 'http://localhost:8087/inbox/'
        resp = cherrypy.serving.response
        resp.headers['X-Powered-By'] = 'https://github.com/jasonzou/pyldn'
        linkStr = '<' + _inbox_url + '>; rel="http://www.w3.org/ns/ldp#inbox", <http://www.w3.org/ns/ldp#Resource>; rel="type", <http://www.w3.org/ns/ldp#RDFSource>; rel="type"'
        log.info(linkStr)
        resp.headers['Link'] = linkStr
        data = "hello --".join(str(reqMethod))
        resp.body = data.encode('utf8')
        resp.headers['Content-Length'] = str(len(resp.body))
        return resp.body

    def GET(self):
        return self.handle_get_post('GET')

    _cp_dispatch = cherrypy.popargs('inboxId')

    def HEAD(self, inboxId=None, *args, **kwargs):
        print(inboxId)
        resp = cherrypy.serving.response
        resp.headers['X-Powered-By'] = 'https://github.com/jasonzou/pyldn'
        resp.headers['Allow'] = "GET, HEAD, OPTIONS, POST"
        resp.headers[
            'Link'] = '<http://www.w3.org/ns/ldp#Resource>; rel="type", <http://www.w3.org/ns/ldp#RDFSource>; rel="type", <http://www.w3.org/ns/ldp#Container>; rel="type", <http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'
        resp.headers['Accept-Post'] = 'application/ld+json, text/turtle'

        return ''
        #return self.handle_get_post('HEAD')

    def POST(self, *args, **kwargs):
        print(args)
        print(kwargs)
        return 'fasdjjadfsfjklda'
        return self.handle_get_post('POST')

    _cp_dispatch = cherrypy.popargs('inboxId')

    def OPTIONS(self, inboxId=None, *args, **kwargs):
        print(args)
        print(kwargs)
        print(inboxId)
        resp = cherrypy.serving.response
        resp.headers['X-Powered-By'] = 'https://github.com/jasonzou/pyldn'
        resp.headers['Allow'] = "GET, HEAD, OPTIONS, POST"
        resp.headers[
            'Link'] = '<http://www.w3.org/ns/ldp#Resource>; rel="type", <http://www.w3.org/ns/ldp#RDFSource>; rel="type", <http://www.w3.org/ns/ldp#Container>; rel="type", <http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'
        resp.headers['Accept-Post'] = 'application/ld+json, text/turtle'

        return ''
    class NonDecoratedPopArgs:
        _cp_dispatch = cherrypy.popargs('a')

        def index(self, a):
            return 'index: ' + str(a)

        index.exposed = True
    class NonDecoratedPopArgs:
        """Test _cp_dispatch = cherrypy.popargs()"""

        _cp_dispatch = cherrypy.popargs('a')

        @cherrypy.expose
        def index(self, a):
            return 'index: ' + str(a)
 class NonDecoratedPopArgs:
     """Test _cp_dispatch = cherrypy.popargs()"""
     
     _cp_dispatch = cherrypy.popargs('a')
     
     def index(self, a):
         return "index: " + str(a)
     index.exposed = True
def setup_server():
    class SubSubRoot:
        @cherrypy.expose
        def index(self):
            return 'SubSubRoot index'

        @cherrypy.expose
        def default(self, *args):
            return 'SubSubRoot default'

        @cherrypy.expose
        def handler(self):
            return 'SubSubRoot handler'

        @cherrypy.expose
        def dispatch(self):
            return 'SubSubRoot dispatch'

    subsubnodes = {
        '1': SubSubRoot(),
        '2': SubSubRoot(),
    }

    class SubRoot:
        @cherrypy.expose
        def index(self):
            return 'SubRoot index'

        @cherrypy.expose
        def default(self, *args):
            return 'SubRoot %s' % (args, )

        @cherrypy.expose
        def handler(self):
            return 'SubRoot handler'

        def _cp_dispatch(self, vpath):
            return subsubnodes.get(vpath[0], None)

    subnodes = {
        '1': SubRoot(),
        '2': SubRoot(),
    }

    class Root:
        @cherrypy.expose
        def index(self):
            return 'index'

        @cherrypy.expose
        def default(self, *args):
            return 'default %s' % (args, )

        @cherrypy.expose
        def handler(self):
            return 'handler'

        def _cp_dispatch(self, vpath):
            return subnodes.get(vpath[0])

    # -------------------------------------------------------------------------
    # DynamicNodeAndMethodDispatcher example.
    # This example exposes a fairly naive HTTP api
    class User(object):
        def __init__(self, id, name):
            self.id = id
            self.name = name

        def __unicode__(self):
            return unicode(self.name)

        def __str__(self):
            return str(self.name)

    user_lookup = {
        1: User(1, 'foo'),
        2: User(2, 'bar'),
    }

    def make_user(name, id=None):
        if not id:
            id = max(*list(user_lookup.keys())) + 1
        user_lookup[id] = User(id, name)
        return id

    @cherrypy.expose
    class UserContainerNode(object):
        def POST(self, name):
            """
            Allow the creation of a new Object
            """
            return 'POST %d' % make_user(name)

        def GET(self):
            return six.text_type(sorted(user_lookup.keys()))

        def dynamic_dispatch(self, vpath):
            try:
                id = int(vpath[0])
            except (ValueError, IndexError):
                return None
            return UserInstanceNode(id)

    @cherrypy.expose
    class UserInstanceNode(object):
        def __init__(self, id):
            self.id = id
            self.user = user_lookup.get(id, None)

            # For all but PUT methods there MUST be a valid user identified
            # by self.id
            if not self.user and cherrypy.request.method != 'PUT':
                raise cherrypy.HTTPError(404)

        def GET(self, *args, **kwargs):
            """
            Return the appropriate representation of the instance.
            """
            return six.text_type(self.user)

        def POST(self, name):
            """
            Update the fields of the user instance.
            """
            self.user.name = name
            return 'POST %d' % self.user.id

        def PUT(self, name):
            """
            Create a new user with the specified id, or edit it if it already
            exists
            """
            if self.user:
                # Edit the current user
                self.user.name = name
                return 'PUT %d' % self.user.id
            else:
                # Make a new user with said attributes.
                return 'PUT %d' % make_user(name, self.id)

        def DELETE(self):
            """
            Delete the user specified at the id.
            """
            id = self.user.id
            del user_lookup[self.user.id]
            del self.user
            return 'DELETE %d' % id

    class ABHandler:
        class CustomDispatch:
            @cherrypy.expose
            def index(self, a, b):
                return 'custom'

        def _cp_dispatch(self, vpath):
            """Make sure that if we don't pop anything from vpath,
            processing still works.
            """
            return self.CustomDispatch()

        @cherrypy.expose
        def index(self, a, b=None):
            body = ['a:' + str(a)]
            if b is not None:
                body.append(',b:' + str(b))
            return ''.join(body)

        @cherrypy.expose
        def delete(self, a, b):
            return 'deleting ' + str(a) + ' and ' + str(b)

    class IndexOnly:
        def _cp_dispatch(self, vpath):
            """Make sure that popping ALL of vpath still shows the index
            handler.
            """
            while vpath:
                vpath.pop()
            return self

        @cherrypy.expose
        def index(self):
            return 'IndexOnly index'

    class DecoratedPopArgs:
        """Test _cp_dispatch with @cherrypy.popargs."""
        @cherrypy.expose
        def index(self):
            return 'no params'

        @cherrypy.expose
        def hi(self):
            return "hi was not interpreted as 'a' param"

    DecoratedPopArgs = cherrypy.popargs('a', 'b',
                                        handler=ABHandler())(DecoratedPopArgs)

    class NonDecoratedPopArgs:
        """Test _cp_dispatch = cherrypy.popargs()"""

        _cp_dispatch = cherrypy.popargs('a')

        @cherrypy.expose
        def index(self, a):
            return 'index: ' + str(a)

    class ParameterizedHandler:
        """Special handler created for each request"""
        def __init__(self, a):
            self.a = a

        @cherrypy.expose
        def index(self):
            if 'a' in cherrypy.request.params:
                raise Exception('Parameterized handler argument ended up in '
                                'request.params')
            return self.a

    class ParameterizedPopArgs:
        """Test cherrypy.popargs() with a function call handler"""

    ParameterizedPopArgs = cherrypy.popargs(
        'a', handler=ParameterizedHandler)(ParameterizedPopArgs)

    Root.decorated = DecoratedPopArgs()
    Root.undecorated = NonDecoratedPopArgs()
    Root.index_only = IndexOnly()
    Root.parameter_test = ParameterizedPopArgs()

    Root.users = UserContainerNode()

    md = cherrypy.dispatch.MethodDispatcher('dynamic_dispatch')
    for url in script_names:
        conf = {
            '/': {
                'user': (url or '/').split('/')[-2],
            },
            '/users': {
                'request.dispatch': md
            },
        }
        cherrypy.tree.mount(Root(), url, conf)
def setup_server():
    class SubSubRoot:

        @cherrypy.expose
        def index(self):
            return 'SubSubRoot index'

        @cherrypy.expose
        def default(self, *args):
            return 'SubSubRoot default'

        @cherrypy.expose
        def handler(self):
            return 'SubSubRoot handler'

        @cherrypy.expose
        def dispatch(self):
            return 'SubSubRoot dispatch'

    subsubnodes = {
        '1': SubSubRoot(),
        '2': SubSubRoot(),
    }

    class SubRoot:

        @cherrypy.expose
        def index(self):
            return 'SubRoot index'

        @cherrypy.expose
        def default(self, *args):
            return 'SubRoot %s' % (args,)

        @cherrypy.expose
        def handler(self):
            return 'SubRoot handler'

        def _cp_dispatch(self, vpath):
            return subsubnodes.get(vpath[0], None)

    subnodes = {
        '1': SubRoot(),
        '2': SubRoot(),
    }

    class Root:

        @cherrypy.expose
        def index(self):
            return 'index'

        @cherrypy.expose
        def default(self, *args):
            return 'default %s' % (args,)

        @cherrypy.expose
        def handler(self):
            return 'handler'

        def _cp_dispatch(self, vpath):
            return subnodes.get(vpath[0])

    # -------------------------------------------------------------------------
    # DynamicNodeAndMethodDispatcher example.
    # This example exposes a fairly naive HTTP api
    class User(object):

        def __init__(self, id, name):
            self.id = id
            self.name = name

        def __unicode__(self):
            return str(self.name)

        def __str__(self):
            return str(self.name)

    user_lookup = {
        1: User(1, 'foo'),
        2: User(2, 'bar'),
    }

    def make_user(name, id=None):
        if not id:
            id = max(*list(user_lookup.keys())) + 1
        user_lookup[id] = User(id, name)
        return id

    @cherrypy.expose
    class UserContainerNode(object):

        def POST(self, name):
            """
            Allow the creation of a new Object
            """
            return 'POST %d' % make_user(name)

        def GET(self):
            return str(sorted(user_lookup.keys()))

        def dynamic_dispatch(self, vpath):
            try:
                id = int(vpath[0])
            except (ValueError, IndexError):
                return None
            return UserInstanceNode(id)

    @cherrypy.expose
    class UserInstanceNode(object):

        def __init__(self, id):
            self.id = id
            self.user = user_lookup.get(id, None)

            # For all but PUT methods there MUST be a valid user identified
            # by self.id
            if not self.user and cherrypy.request.method != 'PUT':
                raise cherrypy.HTTPError(404)

        def GET(self, *args, **kwargs):
            """
            Return the appropriate representation of the instance.
            """
            return str(self.user)

        def POST(self, name):
            """
            Update the fields of the user instance.
            """
            self.user.name = name
            return 'POST %d' % self.user.id

        def PUT(self, name):
            """
            Create a new user with the specified id, or edit it if it already
            exists
            """
            if self.user:
                # Edit the current user
                self.user.name = name
                return 'PUT %d' % self.user.id
            else:
                # Make a new user with said attributes.
                return 'PUT %d' % make_user(name, self.id)

        def DELETE(self):
            """
            Delete the user specified at the id.
            """
            id = self.user.id
            del user_lookup[self.user.id]
            del self.user
            return 'DELETE %d' % id

    class ABHandler:

        class CustomDispatch:

            @cherrypy.expose
            def index(self, a, b):
                return 'custom'

        def _cp_dispatch(self, vpath):
            """Make sure that if we don't pop anything from vpath,
            processing still works.
            """
            return self.CustomDispatch()

        @cherrypy.expose
        def index(self, a, b=None):
            body = ['a:' + str(a)]
            if b is not None:
                body.append(',b:' + str(b))
            return ''.join(body)

        @cherrypy.expose
        def delete(self, a, b):
            return 'deleting ' + str(a) + ' and ' + str(b)

    class IndexOnly:

        def _cp_dispatch(self, vpath):
            """Make sure that popping ALL of vpath still shows the index
            handler.
            """
            while vpath:
                vpath.pop()
            return self

        @cherrypy.expose
        def index(self):
            return 'IndexOnly index'

    class DecoratedPopArgs:

        """Test _cp_dispatch with @cherrypy.popargs."""

        @cherrypy.expose
        def index(self):
            return 'no params'

        @cherrypy.expose
        def hi(self):
            return "hi was not interpreted as 'a' param"
    DecoratedPopArgs = cherrypy.popargs(
        'a', 'b', handler=ABHandler())(DecoratedPopArgs)

    class NonDecoratedPopArgs:

        """Test _cp_dispatch = cherrypy.popargs()"""

        _cp_dispatch = cherrypy.popargs('a')

        @cherrypy.expose
        def index(self, a):
            return 'index: ' + str(a)

    class ParameterizedHandler:

        """Special handler created for each request"""

        def __init__(self, a):
            self.a = a

        @cherrypy.expose
        def index(self):
            if 'a' in cherrypy.request.params:
                raise Exception(
                    'Parameterized handler argument ended up in '
                    'request.params')
            return self.a

    class ParameterizedPopArgs:

        """Test cherrypy.popargs() with a function call handler"""
    ParameterizedPopArgs = cherrypy.popargs(
        'a', handler=ParameterizedHandler)(ParameterizedPopArgs)

    Root.decorated = DecoratedPopArgs()
    Root.undecorated = NonDecoratedPopArgs()
    Root.index_only = IndexOnly()
    Root.parameter_test = ParameterizedPopArgs()

    Root.users = UserContainerNode()

    md = cherrypy.dispatch.MethodDispatcher('dynamic_dispatch')
    for url in script_names:
        conf = {
            '/': {
                'user': (url or '/').split('/')[-2],
            },
            '/users': {
                'request.dispatch': md
            },
        }
        cherrypy.tree.mount(Root(), url, conf)
Beispiel #7
0
class CCTSearch(object):
    def __init__(self):
        #self.conn = Elasticsearch()
        self.conn = ES(['127.0.0.1:9200'])
        self.index = "cct"
        #self.query = query
        #app.logger.info(query)
    
    exposed = True
    def index(self):
        return "test jjjason"
    
    _cp_dispatch = cherrypy.popargs('id')
    def GET(self, id=None, *args, **kwargs):

        log("-- ES Search::GET ---- ")

        if len(args) > 1:
           #test = self.doQuery(self.id)
           #return test
           raise cherrypy.HTTPError(405, "Not Supported! %d " % len(args))
        else:
           if len(kwargs) >= 1:
              self.id = kwargs['search']
              self.searchOption = kwargs['searchOption']
              log("ip =====" + self.searchOption)

              self.direction = 'searchAll'
              #raise cherrypy.HTTPRedirect('/cct2/concepts/%s.all' % self.id)
              test = self.search(self.id)
              return test
           else:
              test = self.search(self.id)
              #raise cherrypy.HTTPError(405, "Not Supported - normal! )%s" % self.id)
              if self.format == 'html':
                 test1 = '<html><head><title>terminology web service</title></head><body>%s </body></html>' % (test)
              else:
                 test1 = test
              return test
            
    def search(self, query):
        #q=TextQuery("_all", query, type="phrase")
        q=MatchQuery("_all", query, type="phrase")
        #s=Search(q)
        resultSet = self.conn.search(query=q, index=self.index)
        myresult = []
        
        id=0
        zh=''
        for item in resultSet:
            id = item._meta.id
            
            tempConcept = CCTConcept(id, item)
            
            if tempConcept.getPrefLabelChn():
                
                zh = tempConcept.getPrefLabelChn()
                pinyin = tempConcept.getPrefLabelPinyin()
            else:
                
                zh = tempConcept.getAltLabelChn()
                pinyin = tempConcept.getAltLabelPinyin()
            
            #if zh != None:
            #log("resulttt =====> " + id)
            #log("resulttt =====> " + zh)
            myresult.append(link(id, pinyin,zh))
        
        templ = pyldnTempl.loader.load('record.html')
        stream = templ.generate(links=self.orderedList(myresult), keyword=query)
        return stream.render("xhtml",doctype="xhtml")
        #return ""
    
    def orderedList(self,myResult):
        ordered = {}
        pinyinList = []
        for item in myResult:
            pinyinList.append(item.predicate)
            ordered[item.predicate] = item
        tempOrderList = sorted(pinyinList)
        newList = []
        for item in tempOrderList:
            newList.append(ordered[item])
        return newList
Beispiel #8
0
        """access control by using ip address"""
        return False
        allowList = ['221.237.0.0/16', '192.168.0.0/16','174.5.0.0/16']
        requestIp = ipaddr.IPv4Address(cherrypy.request.remote.ip)
        for tempNet in allowList:
            allowNet = ipaddr.IPv4Network(tempNet)
            if requestIp in allowNet:
                return False
        return True

    exposed = True
    def index(self):
        return "Things galore!"

    exposed = True
    _cp_dispatch = cherrypy.popargs('id') 
    def GET(self, id=None, *args, **kwargs):
        if len(args) > 1:
           #test = self.doQuery(self.id)
           #return test
           raise cherrypy.HTTPError(405, "Not Supported! %d " % len(args))
        
        conceptid = unicode(str(id), "utf-8")
        self.id = conceptid
        log("============= id => %s" % self.id)
                
        if self.id == 'None':
           self.id = ''

        if self.ipDeny():
            raise cherrypy.HTTPError(403, "Not Supported!")
def setup_server():
    class SubSubRoot:
        def index(self):
            return 'SubSubRoot index'

        index.exposed = True

        def default(self, *args):
            return 'SubSubRoot default'

        default.exposed = True

        def handler(self):
            return 'SubSubRoot handler'

        handler.exposed = True

        def dispatch(self):
            return 'SubSubRoot dispatch'

        dispatch.exposed = True

    subsubnodes = {'1': SubSubRoot(), '2': SubSubRoot()}

    class SubRoot:
        def index(self):
            return 'SubRoot index'

        index.exposed = True

        def default(self, *args):
            return 'SubRoot %s' % (args, )

        default.exposed = True

        def handler(self):
            return 'SubRoot handler'

        handler.exposed = True

        def _cp_dispatch(self, vpath):
            return subsubnodes.get(vpath[0], None)

    subnodes = {'1': SubRoot(), '2': SubRoot()}

    class Root:
        def index(self):
            return 'index'

        index.exposed = True

        def default(self, *args):
            return 'default %s' % (args, )

        default.exposed = True

        def handler(self):
            return 'handler'

        handler.exposed = True

        def _cp_dispatch(self, vpath):
            return subnodes.get(vpath[0])

    class User(object):
        def __init__(self, id, name):
            self.id = id
            self.name = name

        def __unicode__(self):
            return unicode(self.name)

    user_lookup = {1: User(1, 'foo'), 2: User(2, 'bar')}

    def make_user(name, id=None):
        if not id:
            id = max(*user_lookup.keys()) + 1
        user_lookup[id] = User(id, name)
        return id

    class UserContainerNode(object):
        exposed = True

        def POST(self, name):
            return 'POST %d' % make_user(name)

        def GET(self):
            keys = user_lookup.keys()
            keys.sort()
            return unicode(keys)

        def dynamic_dispatch(self, vpath):
            try:
                id = int(vpath[0])
            except (ValueError, IndexError):
                return None

            return UserInstanceNode(id)

    class UserInstanceNode(object):
        exposed = True

        def __init__(self, id):
            self.id = id
            self.user = user_lookup.get(id, None)
            if not self.user and cherrypy.request.method != 'PUT':
                raise cherrypy.HTTPError(404)

        def GET(self, *args, **kwargs):
            return unicode(self.user)

        def POST(self, name):
            self.user.name = name
            return 'POST %d' % self.user.id

        def PUT(self, name):
            if self.user:
                self.user.name = name
                return 'PUT %d' % self.user.id
            else:
                return 'PUT %d' % make_user(name, self.id)

        def DELETE(self):
            id = self.user.id
            del user_lookup[self.user.id]
            del self.user
            return 'DELETE %d' % id

    class ABHandler:
        class CustomDispatch:
            def index(self, a, b):
                return 'custom'

            index.exposed = True

        def _cp_dispatch(self, vpath):
            return self.CustomDispatch()

        def index(self, a, b=None):
            body = ['a:' + str(a)]
            if b is not None:
                body.append(',b:' + str(b))
            return ''.join(body)

        index.exposed = True

        def delete(self, a, b):
            return 'deleting ' + str(a) + ' and ' + str(b)

        delete.exposed = True

    class IndexOnly:
        def _cp_dispatch(self, vpath):
            while vpath:
                vpath.pop()

            return self

        def index(self):
            return 'IndexOnly index'

        index.exposed = True

    class DecoratedPopArgs:
        def index(self):
            return 'no params'

        index.exposed = True

        def hi(self):
            return "hi was not interpreted as 'a' param"

        hi.exposed = True

    DecoratedPopArgs = cherrypy.popargs('a', 'b',
                                        handler=ABHandler())(DecoratedPopArgs)

    class NonDecoratedPopArgs:
        _cp_dispatch = cherrypy.popargs('a')

        def index(self, a):
            return 'index: ' + str(a)

        index.exposed = True

    class ParameterizedHandler:
        def __init__(self, a):
            self.a = a

        def index(self):
            if 'a' in cherrypy.request.params:
                raise Exception(
                    'Parameterized handler argument ended up in request.params'
                )
            return self.a

        index.exposed = True

    class ParameterizedPopArgs:
        pass

    ParameterizedPopArgs = cherrypy.popargs(
        'a', handler=ParameterizedHandler)(ParameterizedPopArgs)
    Root.decorated = DecoratedPopArgs()
    Root.undecorated = NonDecoratedPopArgs()
    Root.index_only = IndexOnly()
    Root.parameter_test = ParameterizedPopArgs()
    Root.users = UserContainerNode()
    md = cherrypy.dispatch.MethodDispatcher('dynamic_dispatch')
    for url in script_names:
        conf = {
            '/': {
                'user': (url or '/').split('/')[-2]
            },
            '/users': {
                'request.dispatch': md
            }
        }
        cherrypy.tree.mount(Root(), url, conf)
def setup_server():
    class SubSubRoot:
        def index(self):
            return "SubSubRoot index"

        index.exposed = True

        def default(self, *args):
            return "SubSubRoot default"

        default.exposed = True

        def handler(self):
            return "SubSubRoot handler"

        handler.exposed = True

        def dispatch(self):
            return "SubSubRoot dispatch"

        dispatch.exposed = True

    subsubnodes = {"1": SubSubRoot(), "2": SubSubRoot()}

    class SubRoot:
        def index(self):
            return "SubRoot index"

        index.exposed = True

        def default(self, *args):
            return "SubRoot %s" % (args,)

        default.exposed = True

        def handler(self):
            return "SubRoot handler"

        handler.exposed = True

        def _cp_dispatch(self, vpath):
            return subsubnodes.get(vpath[0], None)

    subnodes = {"1": SubRoot(), "2": SubRoot()}

    class Root:
        def index(self):
            return "index"

        index.exposed = True

        def default(self, *args):
            return "default %s" % (args,)

        default.exposed = True

        def handler(self):
            return "handler"

        handler.exposed = True

        def _cp_dispatch(self, vpath):
            return subnodes.get(vpath[0])

    # --------------------------------------------------------------------------
    # DynamicNodeAndMethodDispatcher example.
    # This example exposes a fairly naive HTTP api
    class User(object):
        def __init__(self, id, name):
            self.id = id
            self.name = name

        def __unicode__(self):
            return unicode(self.name)

    user_lookup = {1: User(1, "foo"), 2: User(2, "bar")}

    def make_user(name, id=None):
        if not id:
            id = max(*user_lookup.keys()) + 1
        user_lookup[id] = User(id, name)
        return id

    class UserContainerNode(object):
        exposed = True

        def POST(self, name):
            """
            Allow the creation of a new Object
            """
            return "POST %d" % make_user(name)

        def GET(self):
            keys = user_lookup.keys()
            keys.sort()
            return unicode(keys)

        def dynamic_dispatch(self, vpath):
            try:
                id = int(vpath[0])
            except (ValueError, IndexError):
                return None
            return UserInstanceNode(id)

    class UserInstanceNode(object):
        exposed = True

        def __init__(self, id):
            self.id = id
            self.user = user_lookup.get(id, None)

            # For all but PUT methods there MUST be a valid user identified
            # by self.id
            if not self.user and cherrypy.request.method != "PUT":
                raise cherrypy.HTTPError(404)

        def GET(self, *args, **kwargs):
            """
            Return the appropriate representation of the instance.
            """
            return unicode(self.user)

        def POST(self, name):
            """
            Update the fields of the user instance.
            """
            self.user.name = name
            return "POST %d" % self.user.id

        def PUT(self, name):
            """
            Create a new user with the specified id, or edit it if it already exists
            """
            if self.user:
                # Edit the current user
                self.user.name = name
                return "PUT %d" % self.user.id
            else:
                # Make a new user with said attributes.
                return "PUT %d" % make_user(name, self.id)

        def DELETE(self):
            """
            Delete the user specified at the id.
            """
            id = self.user.id
            del user_lookup[self.user.id]
            del self.user
            return "DELETE %d" % id

    class ABHandler:
        class CustomDispatch:
            def index(self, a, b):
                return "custom"

            index.exposed = True

        def _cp_dispatch(self, vpath):
            """Make sure that if we don't pop anything from vpath,
            processing still works.
            """
            return self.CustomDispatch()

        def index(self, a, b=None):
            body = ["a:" + str(a)]
            if b is not None:
                body.append(",b:" + str(b))
            return "".join(body)

        index.exposed = True

        def delete(self, a, b):
            return "deleting " + str(a) + " and " + str(b)

        delete.exposed = True

    class IndexOnly:
        def _cp_dispatch(self, vpath):
            """Make sure that popping ALL of vpath still shows the index 
            handler.
            """
            while vpath:
                vpath.pop()
            return self

        def index(self):
            return "IndexOnly index"

        index.exposed = True

    class DecoratedPopArgs:
        """Test _cp_dispatch with @cherrypy.popargs."""

        def index(self):
            return "no params"

        index.exposed = True

        def hi(self):
            return "hi was not interpreted as 'a' param"

        hi.exposed = True

    DecoratedPopArgs = cherrypy.popargs("a", "b", handler=ABHandler())(DecoratedPopArgs)

    class NonDecoratedPopArgs:
        """Test _cp_dispatch = cherrypy.popargs()"""

        _cp_dispatch = cherrypy.popargs("a")

        def index(self, a):
            return "index: " + str(a)

        index.exposed = True

    class ParameterizedHandler:
        """Special handler created for each request"""

        def __init__(self, a):
            self.a = a

        def index(self):
            if "a" in cherrypy.request.params:
                raise Exception("Parameterized handler argument ended up in request.params")
            return self.a

        index.exposed = True

    class ParameterizedPopArgs:
        """Test cherrypy.popargs() with a function call handler"""

    ParameterizedPopArgs = cherrypy.popargs("a", handler=ParameterizedHandler)(ParameterizedPopArgs)

    Root.decorated = DecoratedPopArgs()
    Root.undecorated = NonDecoratedPopArgs()
    Root.index_only = IndexOnly()
    Root.parameter_test = ParameterizedPopArgs()

    Root.users = UserContainerNode()

    md = cherrypy.dispatch.MethodDispatcher("dynamic_dispatch")
    for url in script_names:
        conf = {"/": {"user": (url or "/").split("/")[-2]}, "/users": {"request.dispatch": md}}
        cherrypy.tree.mount(Root(), url, conf)
Beispiel #11
0
class Inbox(object):

    _cp_dispatch = cherrypy.popargs('inboxId')

    def GET(self, inboxId=None, *args, **kwargs):
        if inboxId:
            return self.get_notification(inboxId)

        request = cherrypy.serving.request
        resp = cherrypy.serving.response
        log.debug("Requested inbox data of {} in {}".format(
            request, request.headers['Accept']))
        if not request.headers['Accept'] or request.headers[
                'Accept'] == '*/*' or 'text/html' in request.headers['Accept']:
            resp.body = inbox_graph.serialize(format='application/ld+json')
            resp.headers['Content-Type'] = 'application/ld+json'
        elif request.headers['Accept'] in ACCEPTED_TYPES:
            resp.body = inbox_graph.serialize(format=request.headers['Accept'])
            resp.headers['Content-Type'] = request.headers['Accept']
        else:
            return 'Requested format unavailable', 415

        resp.headers['X-Powered-By'] = 'https://github.com/jason/pyldn'
        resp.headers['Allow'] = "GET, HEAD, OPTIONS, POST"
        resp.headers[
            'Link'] = '<http://www.w3.org/ns/ldp#Resource>; rel="type", <http://www.w3.org/ns/ldp#RDFSource>; rel="type", <http://www.w3.org/ns/ldp#Container>; rel="type", <http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'
        resp.headers['Accept-Post'] = 'application/ld+json, text/turtle'

        return resp.body

    def POST(self, *args, **kwargs):
        request = cherrypy.serving.request
        log.debug("Received request to create notification")
        log.debug("Headers: {}".format(request.headers))
        log.debug(request.path_info)
        log.debug(request.params)
        print(args)
        print(kwargs)

        dataLen = request.headers['Content-Length']
        print(dataLen)
        rawBody = request.body.read(int(dataLen))

        print(rawBody)
        # Check if there's acceptable content
        content_type = [
            s for s in ACCEPTED_TYPES if s in request.headers['Content-Type']
        ]
        log.debug("Interpreting content type as {}".format(content_type))
        if not content_type:
            return 'Content type not accepted'  #500
        if int(dataLen) <= 0:
            return 'Received empty payload'  # 500

        resp = cherrypy.serving.response

        pyldnConst._ldn_counter += 1

        ldn_url = pyldnConst._inbox_url + '/' + str(pyldnConst._ldn_counter)
        print(ldn_url)
        graphs[ldn_url] = g = Graph()
        try:
            g.parse(data=rawBody, format=content_type[0])
        except:  # Should not catch everything
            return 'Could not parse received {} payload'.format(
                content_type[0])  # 500

        log.debug('Created notification {}'.format(ldn_url))
        inbox_graph.add(
            (URIRef(pyldnConst._inbox_url), ldp['contains'], URIRef(ldn_url)))
        resp.headers['Location'] = ldn_url

        print(inbox_graph.serialize(format='text/turtle'))
        resp.status = 201
        return ldn_url

    def get_notification(self, id):
        request = cherrypy.serving.request
        log.debug("Requested notification data of {}".format(
            request.path_info))
        log.debug("Headers: {}".format(request.headers))

        # Check if the named graph exists
        log.debug("Dict key is {}".format(pyldnConst._inbox_url + '/' + id))

        resp = cherrypy.serving.response
        if pyldnConst._inbox_url + '/' + id not in graphs:
            resp.status = 404
            return 'Requested notification does not exist'

        if 'Accept' not in request.headers or request.headers[
                'Accept'] == '*/*' or 'text/html' in request.headers['Accept']:
            resp.body = graphs[pyldnConst._inbox_url + '/' +
                               id].serialize(format='application/ld+json')
            resp.headers['Content-Type'] = 'application/ld+json'
        elif request.headers['Accept'] in ACCEPTED_TYPES:
            resp.body = graphs[pyldnConst._inbox_url + '/' +
                               id].serialize(format=request.headers['Accept'])
            resp.headers['Content-Type'] = request.headers['Accept']
        else:
            resp.status = 415
            return 'Requested format unavailable'  #, 415

        resp.headers['X-Powered-By'] = 'https://github.com/jason/pyldn'
        resp.headers['Allow'] = "GET"

        return resp.body
def setup_server():

    class SubSubRoot:

        def index(self):
            return 'SubSubRoot index'

        index.exposed = True

        def default(self, *args):
            return 'SubSubRoot default'

        default.exposed = True

        def handler(self):
            return 'SubSubRoot handler'

        handler.exposed = True

        def dispatch(self):
            return 'SubSubRoot dispatch'

        dispatch.exposed = True

    subsubnodes = {'1': SubSubRoot(),
     '2': SubSubRoot()}

    class SubRoot:

        def index(self):
            return 'SubRoot index'

        index.exposed = True

        def default(self, *args):
            return 'SubRoot %s' % (args,)

        default.exposed = True

        def handler(self):
            return 'SubRoot handler'

        handler.exposed = True

        def _cp_dispatch(self, vpath):
            return subsubnodes.get(vpath[0], None)

    subnodes = {'1': SubRoot(),
     '2': SubRoot()}

    class Root:

        def index(self):
            return 'index'

        index.exposed = True

        def default(self, *args):
            return 'default %s' % (args,)

        default.exposed = True

        def handler(self):
            return 'handler'

        handler.exposed = True

        def _cp_dispatch(self, vpath):
            return subnodes.get(vpath[0])

    class User(object):

        def __init__(self, id, name):
            self.id = id
            self.name = name

        def __unicode__(self):
            return unicode(self.name)

    user_lookup = {1: User(1, 'foo'),
     2: User(2, 'bar')}

    def make_user(name, id = None):
        if not id:
            id = max(*user_lookup.keys()) + 1
        user_lookup[id] = User(id, name)
        return id

    class UserContainerNode(object):
        exposed = True

        def POST(self, name):
            return 'POST %d' % make_user(name)

        def GET(self):
            keys = user_lookup.keys()
            keys.sort()
            return unicode(keys)

        def dynamic_dispatch(self, vpath):
            try:
                id = int(vpath[0])
            except (ValueError, IndexError):
                return None

            return UserInstanceNode(id)

    class UserInstanceNode(object):
        exposed = True

        def __init__(self, id):
            self.id = id
            self.user = user_lookup.get(id, None)
            if not self.user and cherrypy.request.method != 'PUT':
                raise cherrypy.HTTPError(404)

        def GET(self, *args, **kwargs):
            return unicode(self.user)

        def POST(self, name):
            self.user.name = name
            return 'POST %d' % self.user.id

        def PUT(self, name):
            if self.user:
                self.user.name = name
                return 'PUT %d' % self.user.id
            else:
                return 'PUT %d' % make_user(name, self.id)

        def DELETE(self):
            id = self.user.id
            del user_lookup[self.user.id]
            del self.user
            return 'DELETE %d' % id

    class ABHandler:

        class CustomDispatch:

            def index(self, a, b):
                return 'custom'

            index.exposed = True

        def _cp_dispatch(self, vpath):
            return self.CustomDispatch()

        def index(self, a, b = None):
            body = ['a:' + str(a)]
            if b is not None:
                body.append(',b:' + str(b))
            return ''.join(body)

        index.exposed = True

        def delete(self, a, b):
            return 'deleting ' + str(a) + ' and ' + str(b)

        delete.exposed = True

    class IndexOnly:

        def _cp_dispatch(self, vpath):
            while vpath:
                vpath.pop()

            return self

        def index(self):
            return 'IndexOnly index'

        index.exposed = True

    class DecoratedPopArgs:

        def index(self):
            return 'no params'

        index.exposed = True

        def hi(self):
            return "hi was not interpreted as 'a' param"

        hi.exposed = True

    DecoratedPopArgs = cherrypy.popargs('a', 'b', handler=ABHandler())(DecoratedPopArgs)

    class NonDecoratedPopArgs:
        _cp_dispatch = cherrypy.popargs('a')

        def index(self, a):
            return 'index: ' + str(a)

        index.exposed = True

    class ParameterizedHandler:

        def __init__(self, a):
            self.a = a

        def index(self):
            if 'a' in cherrypy.request.params:
                raise Exception('Parameterized handler argument ended up in request.params')
            return self.a

        index.exposed = True

    class ParameterizedPopArgs:
        pass

    ParameterizedPopArgs = cherrypy.popargs('a', handler=ParameterizedHandler)(ParameterizedPopArgs)
    Root.decorated = DecoratedPopArgs()
    Root.undecorated = NonDecoratedPopArgs()
    Root.index_only = IndexOnly()
    Root.parameter_test = ParameterizedPopArgs()
    Root.users = UserContainerNode()
    md = cherrypy.dispatch.MethodDispatcher('dynamic_dispatch')
    for url in script_names:
        conf = {'/': {'user': (url or '/').split('/')[-2]},
         '/users': {'request.dispatch': md}}
        cherrypy.tree.mount(Root(), url, conf)