Ejemplo n.º 1
0
class HTTP_API(object):
    """ HTTP API service """
    def __init__(self):
        self._api = API('elmo')
        self._handlers = {}
        self._service = None

    def inject(self, name:APIDependency, dependency:object):
        """
        Inject a Cookie Monster dependency into the service
        
        @param  name        Dependency name
        @param  dependency  Cookie Monster dependency
        """
        handler = name.value()
        handler.inject_dependency(dependency)
        self._handlers[name] = handler

    def listen(self, port:int=5000):
        """
        Check all dependencies are satisfied, define the service and
        start it on a separate thread

        @param  port  The port to listen for HTTP requests
        """
        api = self._api
        dep = self._handlers

        # Check all dependencies are satisfied
        for d in APIDependency:
            if d not in dep:
                raise KeyError('Dependencies not fully satisfied; missing {}'.format(d.name))

        # Build service
        api.create_route('/queue') \
           .set_method_handler(HTTPMethod.GET, dep[APIDependency.CookieJar].GET_queue_length)

        api.create_route('/queue/reprocess') \
           .set_method_handler(HTTPMethod.POST, dep[APIDependency.CookieJar].POST_mark_for_processing)

        api.create_route('/cookiejar') \
            .set_method_handler(HTTPMethod.GET, dep[APIDependency.CookieJar].GET_cookie) \
            .set_method_handler(HTTPMethod.DELETE, dep[APIDependency.CookieJar].DELETE_cookie)

        api.create_route('/cookiejar/<path:identifier>') \
            .set_method_handler(HTTPMethod.GET, dep[APIDependency.CookieJar].GET_cookie) \
            .set_method_handler(HTTPMethod.DELETE, dep[APIDependency.CookieJar].DELETE_cookie)

        api.create_route('/debug/threads') \
            .set_method_handler(HTTPMethod.GET, dep[APIDependency.System].GET_thread_dump)

        # Start service
        self._service = Thread(target=api.listen, args=(port,), daemon=True)
        self._service.start()

    def stop(self):
        """ Stop the running service """
        if self._service.is_alive():
            self._api.stop()
            self._service.join()
Ejemplo n.º 2
0
 def __init__(self):
     self._api = API('elmo')
     self._handlers = {}
     self._service = None