Esempio n. 1
0
    def start(self):
        # setup routing
        route("/display/brightness", method=['OPTIONS',
                                             'POST'])(self.set_brightness)
        route("/mode", method=['OPTIONS', 'POST'])(self.set_mode)
        route("/moodlight/mode", method=['OPTIONS',
                                         'POST'])(self.set_moodlight_mode)

        route("/text", method=['OPTIONS', 'POST'])(self.set_text)

        route("/gameframe", method=['OPTIONS', 'GET'])(self.get_gameframes)
        route("/gameframe", method=['OPTIONS',
                                    'DELETE'])(self.delete_gameframe)
        route("/gameframe/next", method=['OPTIONS',
                                         'POST'])(self.next_gameframe)
        route("/gameframe/current", method=['OPTIONS',
                                            'POST'])(self.set_next_gameframe)

        get("/gameframe/<gameframe>")(self.get_gameframe)
        post("/gameframe/upload/<name>")(self.upload_gameframe)
        post("/gameframe")(self.select_gameframes)

        # run server
        install(EnableCors())
        threading.Thread(target=run,
                         kwargs=dict(host='127.0.0.1',
                                     port=8081,
                                     server=CustomWSGIRefServer,
                                     quiet=True)).start()
Esempio n. 2
0
def main():
    bot = Bot()
    bot.start()

    application = bottle.Bottle()
    bottle.post(path="/webhooks/<name>", callback=bot.webhook)
    bottle.run(application, host='localhost', port=8080)
    def _start_server(self):

        proxy = self

        class BottleServerAdapter(bottle.ServerAdapter):
            def run(self, app):
                class Server(WSGIServer):
                    allow_reuse_address = True

                    def handle_error(self, request, client_address):
                        pass

                class Handler(WSGIRequestHandler):
                    def address_string(self):
                        return self.client_address[0]

                    def log_request(*args, **kwargs):
                        if not self.quiet:
                            return WSGIRequestHandler.log_request(*args, **kwargs)

                self.srv = make_wsgi_server(self.host, self.port, app, Server, Handler)
                proxy.server = self.srv
                self.port = self.srv.server_port
                proxy._started.put(True)
                self.srv.serve_forever(poll_interval=0.1)

        bottle.post("/", callback=self._request_handler)

        def serve():
            bottle.run(host="localhost", port=self.port, quiet=True, server=BottleServerAdapter)

        thread = threading.Thread(target=serve)
        thread.daemon = True
        thread.start()
        return thread
Esempio n. 4
0
 def run(self):
     route('/')(self.handle_index)
     route('/cmds')(self.handle_cmds)
     post('/cmd')(self.handle_cmd_post)
     if self.ssl:
         run(server=self.ssl_server, debug=DEBUG)
     else:
         run(host=self.host, port=self.port, debug=DEBUG)
Esempio n. 5
0
 def test_decorators(self):
     def foo(): return bottle.request.method
     bottle.get('/')(foo)
     bottle.post('/')(foo)
     bottle.put('/')(foo)
     bottle.delete('/')(foo)
     for verb in 'GET POST PUT DELETE'.split():
         self.assertBody(verb, '/', method=verb)
Esempio n. 6
0
    def __init__(self, kernel):
        super(HTTPInterface, self).__init__()

        self.kernel = kernel
        self.id = 'httpinterface'
        self.app = app()
        post('/')(self.handle_request)
        t1 = Thread(target=self.run)
        t1.start()
Esempio n. 7
0
def main():

    urls = [line.strip() for line in sys.stdin]
    extract = Extract(sys.argv[2], urls, int(sys.argv[1]))

    get("/")(extract.start_page)
    post("/")(extract.annotate_page)

    print("Hello human annotator. Visit http://localhost:8080 in your browser.")
    run(host='localhost', port=8080, quiet=True)
def main():
    # Add URL-to-handler mapping
    bottle.post('/')(CustomRequestHandler)

    try:
        # Run server
        bottle.run(host='127.0.0.1', port=8000)

    # If have `KeyboardInterrupt`
    except KeyboardInterrupt:
        # Stop gracefully
        pass
Esempio n. 9
0
 def test_decorators(self):
     app = bottle.Bottle()
     app.route('/g')('foo')
     bottle.route('/g')('foo')
     app.route('/g2', method='GET')('foo')
     bottle.get('/g2')('foo')
     app.route('/p', method='POST')('foo')
     bottle.post('/p')('foo')
     app.route('/p2', method='PUT')('foo')
     bottle.put('/p2')('foo')
     app.route('/d', method='DELETE')('foo')
     bottle.delete('/d')('foo')
     self.assertEqual(app.routes, bottle.app().routes)
Esempio n. 10
0
 def test_decorators(self):
     app = bottle.Bottle()
     app.route('/g')('foo')
     bottle.route('/g')('foo')
     app.route('/g2', method='GET')('foo')
     bottle.get('/g2')('foo')
     app.route('/p', method='POST')('foo')
     bottle.post('/p')('foo')
     app.route('/p2', method='PUT')('foo')
     bottle.put('/p2')('foo')
     app.route('/d', method='DELETE')('foo')
     bottle.delete('/d')('foo')
     self.assertEqual(app.routes, bottle.app().routes)
Esempio n. 11
0
def routeapp(obj):
    for kw in dir(obj):
        attr = getattr(obj, kw)
        if hasattr(attr, 'error'):
            bottle.error(attr.error)(attr)
        if hasattr(attr, 'delete'):
            bottle.delete(attr.delete)(attr)
        if hasattr(attr, 'put'):
            bottle.put(attr.put)(attr)
        if hasattr(attr, 'post'):
            bottle.post(attr.post)(attr)
        if hasattr(attr, 'route'):
            bottle.route(attr.route)(attr)
Esempio n. 12
0
    def serve(self, port):
        model = self._load_model()

        def handler():
            data = request.body.read().decode('utf-8')
            response.content_type = 'text/plain'
            return model.predict(data)

        print(
            """To use the server, run the following command from another shell:
            curl http://localhost:{} --data \"test input here\"""".format(
                port))
        post('/')(handler)
        run(host='localhost', port=port)
Esempio n. 13
0
    def serve(self, port):
        def handler():
            data = request.body.read().decode('utf-8')
            response.content_type = 'text/plain'
            cmd = [self.exe_path, 'predict', data]
            res = run_shell(cmd, capture_output=True)
            return res.rstrip()

        self._build_project(self.sln_path)
        print(
            """To use the server, run the following command from another shell:
            curl http://localhost:{} --data \"test input here\"""".format(
                port))
        post('/')(handler)
        run(host='localhost', port=port)
Esempio n. 14
0
    def _start_server(self):

        proxy = self

        class BottleServerAdapter(bottle.ServerAdapter):

            def run(self, app):

                class Server(WSGIServer):
                    allow_reuse_address = True

                    def handle_error(self, request, client_address):
                        pass

                class Handler(WSGIRequestHandler):
                    def address_string(self):
                        return self.client_address[0]

                    def log_request(*args, **kwargs):
                        if not self.quiet:
                            return WSGIRequestHandler.log_request(
                                *args, **kwargs)

                self.srv = make_wsgi_server(
                    self.host,
                    self.port,
                    app,
                    Server,
                    Handler)
                proxy.server = self.srv
                self.port = self.srv.server_port
                proxy._started.put(True)
                self.srv.serve_forever(poll_interval=0.1)

        bottle.post('/', callback=self._request_handler)

        def serve():
            bottle.run(
                host='localhost',
                port=self.port,
                quiet=True,
                server=BottleServerAdapter)
        thread = threading.Thread(target=serve)
        thread.daemon = True
        thread.start()
        return thread
Esempio n. 15
0
    def __init__(self, path):
        if path not in endpoint_map:
            self._endpoint = JsonRpcHandler(path)

            # register with bottle
            def handle_rpc():
                json_body = {}
                try:
                    if bottle.request.headers['CONTENT_TYPE'] \
                       not in ('application/json', 'application/json-rpc'):
                        raise ParseError(
                            message='Invalid content type.',
                            data=bottle.request.headers['CONTENT_TYPE'])
                    try:
                        json_body = bottle.json_loads(
                            bottle.request.body.read())
                    except ValueError as err:
                        raise ParseError(message='Invalid JSON.',
                                         data=json.dumps(
                                             traceback.format_exc()))

                    response = self._endpoint.rpc(json_body)
                    # If we have error set the HTTP status code
                    if 'error' in response:
                        error = response['error']
                        status = jsonrpc_code_to_status.get(error['code'], 500)
                        bottle.response.status = status

                    return response
                except JsonRpcError as err:
                    return jsonrpc_message({
                        'id': json_body.get('id'),
                        'error': err.to_json()
                    })

            post(path, callback=handle_rpc)

            # In bottle /path/ and /path are two different routes, because of
            # http://www.ietf.org/rfc/rfc3986.txt, so register them both
            if path[-1] != '/' and path[-1] != '>':
                post('%s/' % path, callback=handle_rpc)

            endpoint_map[path] = self._endpoint
        else:
            self._endpoint = endpoint_map[path]
Esempio n. 16
0
    def __init__(self, path):
        if path not in endpoint_map:
            self._endpoint = JsonRpcHandler(path)

            # register with bottle
            def handle_rpc():
                json_body = {}
                try:
                    if bottle.request.headers['CONTENT_TYPE'] \
                       not in ('application/json', 'application/json-rpc'):
                        raise ParseError(
                            message='Invalid content type.',
                            data=bottle.request.headers['CONTENT_TYPE'])
                    try:
                        json_body = bottle.json_loads(
                            bottle.request.body.read())
                    except ValueError as err:
                        raise ParseError(
                            message='Invalid JSON.',
                            data=json.dumps(traceback.format_exc()))

                    response = self._endpoint.rpc(json_body)
                    # If we have error set the HTTP status code
                    if 'error' in response:
                        error = response['error']
                        status = jsonrpc_code_to_status.get(error['code'], 500)
                        bottle.response.status = status

                    return response
                except JsonRpcError as err:
                    return jsonrpc_message({
                        'id': json_body.get('id'),
                        'error': err.to_json()
                    })

            post(path, callback=handle_rpc)

            # In bottle /path/ and /path are two different routes, because of
            # http://www.ietf.org/rfc/rfc3986.txt, so register them both
            if path[-1] != '/' and path[-1] != '>':
                post('%s/' % path, callback=handle_rpc)

            endpoint_map[path] = self._endpoint
        else:
            self._endpoint = endpoint_map[path]
Esempio n. 17
0
    def run(self):
        # UI Functions
        route('/')(self.frontend)
        # route('/', method='OPTIONS')(self.options_handler)
        # route('/<path:path>', method='OPTIONS')(self.options_handler)
        # hook('after_request')(self.enable_cors)

        # API functions
        # v1
        route('/api/v1/')(self.index)
        route('/api/v1/status')(self.status)
        route('/api/v1/stations')(self.stations)
        route('/api/v1/streams')(self.streams)
        route('/api/v1/<station>/streams')(self.streams)
        route('/api/v1/<station>')(self.station)
        post('/api/v1/<station>')(self.set)
        route('/api/v1/<station>/<stream>')(self.stream)
        post('/api/v1/<station>/<stream>')(self.set)
        route('/api/v1/play')(self.play)
        route('/api/v1/pause')(self.pause)
        route('/api/v1/stop')(self.stop)

        # API functions
        # v1.1
        route('/api/v1.1/stations')(self.stations)
        route('/api/v1.1/stations/<station>')(self.station)
        route('/api/v1.1/stations/<station>/streams')(self.streams)
        route('/api/v1.1/stations/<station>/streams/<stream>')(self.stream)
        route('/api/v1.1/streams')(self.streams)
        route('/api/v1.1/streams/<station>')(self.streams)
        route('/api/v1.1/streams/<station>/<stream>')(self.stream)
        route('/api/v1.1/player')(self.status)
        post('/api/v1.1/player')(self.play)
        post('/api/v1.1/player/<station>/<stream>')(self.play)
        post('/api/v1.1/volume/<value>')(self.volume)
        put('/api/v1.1/player')(self.pause)
        delete('/api/v1.1/player')(self.stop)
        try:
            run(host=self.host, port=self.port,
                debug=BOTTLE_DEBUG, quiet=not BOTTLE_DEBUG)
        except (OSError, OverflowError) as exc_info:
            print("SERVER ERROR: %s." % exc_info)
            print("Check network settings (host, port) in config")
            sys.exit(1)
Esempio n. 18
0
def say_thanks():
    tweet = request.forms.get('tweet')
    answer = request.forms.get('answer')
    clean_tweet = request.forms.get('clean_tweet')

    # Write all checked tweets into the file
    if answer == 'Correct':
        data = [str(4), tweet]
    elif answer == 'Positive':
        data = [str(4), tweet]
        white_list[clean_tweet] = 'Negative'
    elif answer == 'Negative':
        data = [str(4), tweet]
        white_list[clean_tweet] = 'Positive'
    with open('results.csv', 'wb') as fp:
        a = csv.writer(fp, delimiter=',')
        a.writerow(data)

    # Go to initial page.
    post()
    return '''
    def setup_webserver(self):
        bottle.route('/')(bottle.view('index')(self.index))

        bottle.post('/clear_log')(self.clear_log)
        bottle.post('/config')(self.config)
        bottle.post('/function/<function_id>')(self.function)
        bottle.run(host='0.0.0.0', port=8080)
	def setup_webserver(self):
		bottle.route('/')(bottle.view('index')(self.index))

		bottle.post('/clear_log')(self.clear_log)
		bottle.post('/config')(self.config)
		bottle.post('/function/<function_id>')(self.function)
		bottle.run(host='0.0.0.0', port=8080)
Esempio n. 21
0
def rpc( path ):
  # Create route for bottle
  bottleRpcFn = bottle.post( path )

  def wrap( clas ):
    if not isinstance( clas, type ):
      raise TypeError( 'Only classes are supported. Got {}.'.format( type( clas ) ) )

    servedObject = clas()
    dispatchJsonRpc = pjsonrpc.JsonRpcDispatcher( servedObject )

    def rpcCallWrap():
      response = dispatchJsonRpc( bottle.request.body )
      return response

    # Map the rpcCallWrap to created bottle route
    return bottleRpcFn( rpcCallWrap )

  return wrap
Esempio n. 22
0
    def run(self):
        # UI Functions
        route('/')(self.frontend)
        # route('/', method='OPTIONS')(self.options_handler)
        # route('/<path:path>', method='OPTIONS')(self.options_handler)
        # hook('after_request')(self.enable_cors)

        # API functions
        # v1
        route('/api/v1/')(self.index)
        route('/api/v1/status')(self.status)
        route('/api/v1/stations')(self.stations)
        route('/api/v1/streams')(self.streams)
        route('/api/v1/<station>/streams')(self.streams)
        route('/api/v1/<station>')(self.station)
        post('/api/v1/<station>')(self.set)
        route('/api/v1/<station>/<stream>')(self.stream)
        post('/api/v1/<station>/<stream>')(self.set)
        route('/api/v1/play')(self.play)
        route('/api/v1/pause')(self.pause)
        route('/api/v1/stop')(self.stop)

        # API functions
        # v1.1
        route('/api/v1.1/stations')(self.stations)
        route('/api/v1.1/stations/<station>')(self.station)
        route('/api/v1.1/stations/<station>/streams')(self.streams)
        route('/api/v1.1/stations/<station>/streams/<stream>')(self.stream)
        route('/api/v1.1/streams')(self.streams)
        route('/api/v1.1/streams/<station>')(self.streams)
        route('/api/v1.1/streams/<station>/<stream>')(self.stream)
        route('/api/v1.1/player')(self.status)
        post('/api/v1.1/player')(self.play)
        post('/api/v1.1/player/<station>/<stream>')(self.play)
        put('/api/v1.1/player')(self.pause)
        delete('/api/v1.1/player')(self.stop)
        run(host=self.host,
            port=self.port,
            debug=BOTTLE_DEBUG,
            quiet=not BOTTLE_DEBUG)
Esempio n. 23
0
    def run(self):
        # UI Functions
        route('/')(self.frontend)
        # route('/', method='OPTIONS')(self.options_handler)
        # route('/<path:path>', method='OPTIONS')(self.options_handler)
        # hook('after_request')(self.enable_cors)

        # API functions
        # v1
        route('/api/v1/')(self.index)
        route('/api/v1/status')(self.status)
        route('/api/v1/stations')(self.stations)
        route('/api/v1/streams')(self.streams)
        route('/api/v1/<station>/streams')(self.streams)
        route('/api/v1/<station>')(self.station)
        post('/api/v1/<station>')(self.set)
        route('/api/v1/<station>/<stream>')(self.stream)
        post('/api/v1/<station>/<stream>')(self.set)
        route('/api/v1/play')(self.play)
        route('/api/v1/pause')(self.pause)
        route('/api/v1/stop')(self.stop)

        # API functions
        # v1.1
        route('/api/v1.1/stations')(self.stations)
        route('/api/v1.1/stations/<station>')(self.station)
        route('/api/v1.1/stations/<station>/streams')(self.streams)
        route('/api/v1.1/stations/<station>/streams/<stream>')(self.stream)
        route('/api/v1.1/streams')(self.streams)
        route('/api/v1.1/streams/<station>')(self.streams)
        route('/api/v1.1/streams/<station>/<stream>')(self.stream)
        route('/api/v1.1/player')(self.status)
        post('/api/v1.1/player')(self.play)
        post('/api/v1.1/player/<station>/<stream>')(self.play)
        put('/api/v1.1/player')(self.pause)
        delete('/api/v1.1/player')(self.stop)
        run(host=self.host, port=self.port,
            debug=BOTTLE_DEBUG, quiet=not BOTTLE_DEBUG)
Esempio n. 24
0
def bottle_post(url_path: str) -> Callable[[AnyFunction], AnyFunction]:
    return bottle.post(url_path)  # type: ignore
Esempio n. 25
0
        for chapter in session.query(Chapter).\
                filter(Chapter.id==id).order_by(Chapter.id):
            chapters[chapter.id] = chapter

        all_chapters = {}
        for row in session.query(Chapter).order_by(Chapter.id):
            all_chapters[row.id] = db_object_to_dict(row)

        characters = {}
        for row in session.query(Character).order_by(Character.id):
            characters[row.id] = db_object_to_dict(row)

        passages = {}
        for row in session.query(Passage).\
                filter(Passage.chapter_id==id).order_by(Passage.passage_order):
            row.body = '<br />'.join(row.body.splitlines())
            passages[row.id] = db_object_to_dict(row)

        cp = app.get_config()
        splash_images_url = cp.get('paths', 'splash_images_url')

        return render('chapters/view.html', {'all_chapters': all_chapters, 'chapters': chapters, 'characters': characters, 'passages': passages, 'splash_images_url': splash_images_url})

go = Chapters()
route('/chapters/all')(go.all)
route('/chapters/create')(go.create)
route('/chapters/edit/:id')(go.edit)
route('/chapters/index')(go.index)
post('/chapters/save')(go.save)
route('/chapters/view/:id')(go.view)
Esempio n. 26
0
 def multi(method_):
     def with_input():
         return method_(request.json)
     return post(path)(self.build_method(timeout, with_input))
Esempio n. 27
0
def create_rest_api(base_collection, url_base, restricted=False, override_={}, post_={}):
    def list_collection(**context):
        collection = base_collection.fetch(**context)
        bottle.response.context.update({'collection': collection})
        return collection
    def update_collection(**context): pass
    def add_to_collection(**context):
        new_item = bottle.request.json
        new_item['user'] = context['user']
        item = base_collection.new(**new_item)
        bottle.response.context.update({'item': item})
        return item
    def delete_collection(**context): pass
    def show_item(id, **context):
        item = base_collection.get(_id=id)
        bottle.response.context.update({'item': item})
        return item
    def update_item(id, **context):
        updated_item = bottle.request.json
        updated_item['_id'] = id
        item = base_collection.update(**updated_item)
        bottle.response.context.update({'item': item})
        return item
    def add_to_item(id, **context): pass
    def delete_item(id, **context):
        base_collection.remove(_id=id)
        return list_collection(**context)
    route_map = {
        # Collections
        '%s' % url_base: list_collection,
        '>%s' % url_base: update_collection,
        '#%s' % url_base: add_to_collection,
        'X%s' % url_base: delete_collection,
        # Entities
        '%s/:id' % url_base: show_item,
        '>%s/:id' % url_base: update_item,
        '#%s/:id' % url_base: add_to_item,
        'X%s/:id' % url_base: delete_item,
    }
    template_map = {
        # Collections
        list_collection: 'list',
        update_collection: 'list',
        add_to_collection: 'show',
        delete_collection: 'list',
        # Entities
        show_item: 'show',
        update_item: 'show',
        add_to_item: 'show',
        delete_item: 'list',
    }

    # Create the full callback for a route and action
    def make_templated_callback(callback):
        template_base = 'generic/'
        def wrapper(**context):
            #print context
            context['user'] = bottle.response.context.user.id
            cb=callback
            if override_.has_key(callback.__name__): cb = override_[callback.__name__]
            result = cb(**context)
            if post_.has_key(callback.__name__): result = post_[cb.__name__](**result)
            return render(template_base + template_map[callback], **result)
        if restricted: wrapper = require_auth(wrapper)
        return wrapper
    # Make a JSON version too
    def make_json_callback(callback):
        def wrapper(**context):
            context['user'] = bottle.response.context.user.id
            cb=callback
            if override_.has_key(callback.__name__): cb = override_[callback.__name__]
            #print "CONTEXT: %s" % context
            result = cb(**context)
            if post_.has_key(callback.__name__): result = post_[cb.__name__](**result)
            #print "RESULT: %s" % result
            return pymongo_to_json(result)
        if restricted: wrapper = require_auth(wrapper)
        return wrapper

    # Generate the routes
    for route in route_map.items():
        path, callback = route
        if path.startswith('#'):
            bottle.post(path[1:] + '.json')(make_json_callback(callback))
            bottle.post(path[1:])(make_templated_callback(callback))
        elif path.startswith('X'):
            bottle.delete(path[1:] + '.json')(make_json_callback(callback))
            bottle.delete(path[1:])(make_templated_callback(callback))
        elif path.startswith('>'):
            bottle.put(path[1:] + '.json')(make_json_callback(callback))
            bottle.put(path[1:])(make_templated_callback(callback))
        else:
            bottle.get(path + '.json')(make_json_callback(callback))
            bottle.get(path)(make_templated_callback(callback))
Esempio n. 28
0
def init():
    route('/')(Main_H)
    route('/:argument')(Main_H)
    route('/test/:argument')(Main_H)
    get('/a/b')(Main_H)
    post('/a/b')(Main_H)
Esempio n. 29
0
 def setup_routes(self):
     bottle.post('/emu_reports/performance_report')(self.performance_report)
     bottle.post('/emu_reports/task_complete')(self.task_complete)
    }


@bottle.post('/move')
def move():
    data = bottle.request.json

    # TODO: Do things with data

    #directions = ['up', 'down', 'left', 'right']
    gs = game_state(data)
    #direction = flood_fill(gs, 20)
    direction = 'left'
    print direction
    return {'move': direction, 'taunt': 'battlesnake-python!'}


# Expose WSGI app (so gunicorn can find it)
application = bottle.default_app()

if __name__ == '__main__':
    gs = game_state(game_state.get_example_raw())
    direction = flood_fill(gs, 10)
    print direction
    bottle.run(application,
               host=os.getenv('IP', '0.0.0.0'),
               port=os.getenv('PORT', '8080'),
               debug=True)
    print "main.py"
    bottle.post(game_state.get_example_raw())
Esempio n. 31
0
class App():

    def __init__(self):
        #self.battlesnake = Battlesnake()

    def run(self):
        bottle.run(
            application,
            host=os.getenv('IP', '0.0.0.0'),
            port=os.getenv('PORT', '8080'),
            debug=os.getenv('DEBUG', True)
        )

    def index(self):
        return '''
        Battlesnake documentation can be found at
           <a href="https://docs.battlesnake.io">https://docs.battlesnake.io</a>.
        '''

    def static(path):
        """
        Given a path, return the static file located relative
        to the static folder.

        This can be used to return the snake head URL in an API response.
        """
        return bottle.static_file(path, root='static/')

    def ping(self):
        """
        A keep-alive endpoint used to prevent cloud application platforms,
        such as Heroku, from sleeping the application instance.
        """
        return ping_response()


    def start(self):
        data = bottle.request.json

        """
        TODO: If you intend to have a stateful snake AI,
                initialize your snake state here using the
                request's data if necessary.
        """
        print(json.dumps(data))
        
        #self.battlesnake.start(data)
        print("Snek Started")
        #action, _, _, _ =  self.battlesnake.act(data)


        color = "#342D7E"

        return start_response(color)


    def move(self):
        data = bottle.request.json

        """
        TODO: Using the data from the endpoint request object, your
                snake AI must choose a direction to move in.
        """
        print(json.dumps(data))

        directions = ['up', 'down', 'left', 'right']

        #action, _, _, _ =  self.battlesnake.act(data)

        direction = directions[0]#action]
        print(direction)

        return move_response(direction)


    def end(self):
        data = bottle.request.json

        """
        TODO: If your snake AI was stateful,
            clean up any stateful objects here.
        """
        print(json.dumps(data))

        return end_response()



# Expose WSGI app (so gunicorn can find it)
application = bottle.default_app()




if __name__ == '__main__':
    app = App()
    bottle.route('/')(app.index)
    bottle.route('/static/<path:path>')(app.static)
    bottle.post('/ping')(app.ping)
    bottle.post('/start')(app.start)
    bottle.post('/move')(app.move)
    bottle.post('/end')(app.end)
    app.run()
Esempio n. 32
0
        session.commit()
        redirect('/characters/all')

    def view(self, id):
        """character information"""
        session = dbengine.connect()

        all_characters = {}
        for row in session.query(Character).order_by(Character.id):
            all_characters[row.id] = db_object_to_dict(row)

        characters = {}
        for character in session.query(Character).\
                filter(Character.id==id).order_by(Character.id.desc()):
            characters[character.id] = character

        return render('characters/view.html', {
            'all_characters': all_characters,
            'characters': characters
        })


go = Characters()
route('/characters/all')(go.all)
route('/characters/create')(go.create)
route('/characters/edit/:id')(go.edit)
route('/characters/index')(go.index)
post('/characters/save')(go.save)
route('/characters/view/:id')(go.view)
Esempio n. 33
0
    '/'+_node_id_: [authenticate, show_node],
    '>/'+_node_id_: [authenticate, update_node],
    'X/'+_node_id_: [authenticate, delete_node],
}

# Define routes from the route map
def make_route_callback(callback):
    if type(callback) == list: callback = partial(*callback)
    def wrapper(**context):
        return callback(**get_session(**start_context(**context)))
    return wrapper

for route in route_map.items():
    path, callback = route
    if path.startswith('#'):
        bottle.post(path[1:])(make_route_callback(callback))
    elif path.startswith('X'):
        bottle.delete(path[1:])(make_route_callback(callback))
    elif path.startswith('>'):
        bottle.put(path[1:])(make_route_callback(callback))
    else:
        bottle.get(path)(make_route_callback(callback))

# Static fallback
@bottle.route('/<filepath:path>')
def static_file(filepath):
    return bottle.static_file(filepath, root='./static/')

# Run the server
bottle.debug(config.debug)
bottle.run(server=config.server, host='0.0.0.0', port=config.port, reloader=config.debug)
Esempio n. 34
0
            update.chapter_id = chapter_id
            update.passage_order = passage_order
            update.soliloquy = soliloquy
        else:
            # create
            new_passage = Passage(body, character_id, chapter_id,
                                  passage_order, soliloquy)
            session.add(new_passage)

        session.commit()
        redirect('/passages/all')

    def view(self, id):
        """passage information"""
        session = dbengine.connect()

        passages = {}
        for passage in session.query(Passage).\
                filter(Passage.id==id).order_by(Passage.id.desc()):
            passages[passage.id] = passage

        return render('passages/view.html', {'passages': passages})


go = Passages()
route('/passages/all')(go.all)
route('/passages/create')(go.create)
route('/passages/edit/:id')(go.edit)
post('/passages/save')(go.save)
route('/passages/view/:id')(go.view)
Esempio n. 35
0
    s = Server(
        args.client_hostnames,
        args.benchmark_time,
        args.chunk_size,
        args.file_size,
        args.heartbeat_interval,
        args.monitoring_interval,
        args.port,
        args.log
    )

    # Initialize routes
    bottle.get("/")(s.main)
    bottle.get("/status")(s.status)
    bottle.get("/report")(s.report)
    bottle.get("/logs")(s.logs)
    bottle.get("/about")(s.about)
    bottle.route('/static/:file_path#.+#')(s.static)
    bottle.get("/favicon.ico")(s.get_favicon)

    bottle.post("/hello")(s.hello)
    bottle.post(HEARTBEAT_PATH)(s.client_heartbeat)
    bottle.post(START_PATH)(s.client_start)
    bottle.post(STOP_PATH)(s.client_stop)
    bottle.post(RESOURCES_PATH)(s.client_resources)
    bottle.post(ROLLOVER_PATH)(s.client_rollover)

    s.run_benchmarks()
    bottle.run(host='localhost', port=args.port, debug=True, quiet=True)
    s.client_thread.join()
Esempio n. 36
0
    def __init__(self, bikaApi, irodsApi):
        # Web service methods
        post('/bika/login')(bikaApi.login)
        post('/bika/get/clients')(bikaApi.get_clients)
        post('/bika/get/contacts')(bikaApi.get_contacts)
        post('/bika/get/samples')(bikaApi.get_samples)
        post('/bika/get/analysis_requests')(bikaApi.get_analysis_requests)
        post('/bika/get/arimports')(bikaApi.get_arimports)
        post('/bika/get/batches')(bikaApi.get_batches)
        post('/bika/get/worksheets')(bikaApi.get_worksheets)
        post('/bika/get/invoices')(bikaApi.get_invoices)
        post('/bika/get/price_list')(bikaApi.get_price_list)
        post('/bika/get/supply_orders')(bikaApi.get_supply_orders)
        post('/bika/get/lab_products')(bikaApi.get_lab_products)
        post('/bika/get/storage_locations')(bikaApi.get_storage_locations)
        post('/bika/get/artemplates')(bikaApi.get_artemplates)
        post('/bika/get/analysis_profiles')(bikaApi.get_analysis_profiles)
        post('/bika/get/analysis_services')(bikaApi.get_analysis_services)
        post('/bika/get/sample_types')(bikaApi.get_sample_types)
        post('/bika/get/users')(bikaApi.get_users)
        post('/bika/get/manager_users')(bikaApi.get_manager_users)
        post('/bika/get/analyst_users')(bikaApi.get_analyst_users)
        post('/bika/get/clerk_users')(bikaApi.get_clerk_users)
        post('/bika/get/client_users')(bikaApi.get_client_users)

        post('/bika/set/analysis_result')(bikaApi.set_analysis_result)
        post('/bika/set/analyses_results')(bikaApi.set_analyses_results)

        post('/bika/update/batch')(bikaApi.update_batch)
        post('/bika/update/batches')(bikaApi.update_batches)
        post('/bika/update/analysis_request')(bikaApi.update_analysis_request)
        post('/bika/update/analysis_requests')(bikaApi.update_analysis_requests)
        post('/bika/update/worksheet')(bikaApi.update_worksheet)
        post('/bika/update/worksheets')(bikaApi.update_worksheets)
        post('/bika/update/supply_order')(bikaApi.update_supply_order)
        post('/bika/update/supply_orders')(bikaApi.update_supply_orders)
        post('/bika/update/lab_product')(bikaApi.update_lab_product)
        post('/bika/update/lab_products')(bikaApi.update_lab_products)

        post('/bika/cancel/batch')(bikaApi.cancel_batch)
        post('/bika/cancel/worksheet')(bikaApi.update_worksheets)
        post('/bika/cancel/analysis_request')(bikaApi.cancel_analysis_request)
        post('/bika/reinstate/batch')(bikaApi.reinstate_batch)
        post('/bika/reinstate/worksheet')(bikaApi.update_worksheets)
        post('/bika/reinstate/analysis_request')(bikaApi.reinstate_analysis_request)

        post('/bika/action/receive_sample')(bikaApi.receive_sample)
        post('/bika/action/close_batch')(bikaApi.close_batch)
        post('/bika/action/open_batch')(bikaApi.open_batch)
        post('/bika/action/close_worksheet')(bikaApi.update_worksheets)
        post('/bika/action/open_worksheet')(bikaApi.update_worksheets)
        post('/bika/action/submit')(bikaApi.submit)
        post('/bika/action/verify')(bikaApi.verify)
        post('/bika/action/publish')(bikaApi.publish)
        post('/bika/action/republish')(bikaApi.republish)
        post('/bika/action/activate_supply_order')(bikaApi.activate_supply_order)
        post('/bika/action/deactivate_supply_order')(bikaApi.deactivate_supply_order)
        post('/bika/action/dispatch_supply_order')(bikaApi.dispatch_supply_order)
        post('/bika/action/activate_lab_product')(bikaApi.activate_lab_product)
        post('/bika/action/deactivate_lab_product')(bikaApi.deactivate_lab_product)

        post('/bika/create/batch')(bikaApi.create_batch)
        post('/bika/create/analysis_request')(bikaApi.create_analysis_request)
        post('/bika/create/worksheet')(bikaApi.create_worksheet)
        post('/bika/create/supply_order')(bikaApi.create_supply_order)
        post('/bika/create/lab_product')(bikaApi.create_lab_product)

        post('/bika/count/analysis_requests')(bikaApi.count_analysis_requests)
        post('/bika/count/samples')(bikaApi.count_samples)

        post('/irods/get/running')(irodsApi.get_running_folders)
        post('/irods/put/samplesheet')(irodsApi.put_samplesheet)

        # check status
        post('/web/check/status')(self.test_server)
        post('/bika/check/status')(bikaApi.test_server)
        post('/irods/check/status')(irodsApi.test_server)
Esempio n. 37
0
        else:
            # create
            new_character = Character(name, alias, location_id)
            session.add(new_character)

        session.commit()
        redirect('/characters/all')
 
    def view(self, id):
        """character information"""
        session = dbengine.connect()

        all_characters = {}
        for row in session.query(Character).order_by(Character.id):
            all_characters[row.id] = db_object_to_dict(row)

        characters = {}
        for character in session.query(Character).\
                filter(Character.id==id).order_by(Character.id.desc()):
            characters[character.id] = character

        return render('characters/view.html', {'all_characters': all_characters, 'characters': characters})

go = Characters()
route('/characters/all')(go.all)
route('/characters/create')(go.create)
route('/characters/edit/:id')(go.edit)
route('/characters/index')(go.index)
post('/characters/save')(go.save)
route('/characters/view/:id')(go.view)
Esempio n. 38
0
 def __new__(cls, *args, **kwargs):
     obj = super(Cerberus, cls).__new__(cls, *args, **kwargs)
     bottle.post("/")(obj.http_api_handler)
     return obj
Esempio n. 39
0
def haikuports_hook():
    payload = request.forms.get('payload')
    d = json.loads(payload)
    h = hooks.Haikuports_Commit(d)
    for k in h.commits:
        dumby = Dumby_Commit( ('hp-trunk', (k['sha'], time.time()) )
        new_commit(k['name'], dumby)

def new_commit(name, commits):
    db = get_db()
    if name not in db.keys():
        pass
    if name not in db:
        db[name] = {}
        db[name]['revs'] = {}
    else:
        #Tuple (branch , (commit-sha, unix_time))
        for commit in commits.commits: 
            #Tuple of time of commit and commit ID.
            db[name]['revs'][commit[0]] = {}
            db[name]['revs'][commit[0]]['last-commit'] = (commit[1][1], commit[1][0])
            db[name]['revs'][commit[0]][commit[1][0]] = {'Builds': 0}

def mk_id(name, arch, gcc, length=6):
    u = uuid.uuid4().hex[:length] #This reduces the uniqueness but makes better urls
    jobid = name +'-'+ arch +'-'+ gcc +'-'+ u
    return jobid

@post('/completed')
def recieve_blob():
    db = get_db()
    info = json.loads(request.forms.get('json'))
    if 'jobs' not in  get_db():
        get_db()['jobs'] = {}
    db['jobs'][info['job_id']] = {'status': 'completed', 
    'blob': info['blobref'], 'date': time.time()}
    which = db[info['project']]['revs'][info['branch']][info['sha']]
    which['Builds'] += 1
    if 'Jobs' in which:
        which['Jobs'].append(info['job_id'])
    else:
        which['Jobs'] = [info['job_id']]


@route("/blob/:job_id")
def give_blob(job_id):
    return get_db()['jobs'][job_id]['blob']

@error(404)
def error404(e):
    img = random.choice([x for x in os.listdir('css/neko100') if x[0] != '.']) 
    # I have a .DS_Store from OSX might have other weird stuff on other platforms
    return "<!DOCTYPE html><html><head><title>Error 404: Cat Found</title></head><body style='text-align:center;'><img src='/css/neko100/%s'><p><a href='http://www.cavestory.org/othergames_neko100.php'>src</a></p></body></html>" % img
@route('/css/:filename#.+#')
def css_static(filename):
    return static_file(filename, root='./css')
    

def get_db():
    return our_db

def close_pickle(db):
    with open('data.pkl', 'wb') as f:
        cPickle.dump(db, f)

class Job(object):
    "Unused and unuseful, contains a good line for evaluating jobs of a specific project"
    def __init__(self, name, database):
        self.start =  time.localtime()
        self.name = name
        self.database = database
        self.vcs = self.lookup_vcs()
    def __setattr__(self, key, value):
        self.database[self.name][key] = value
    def __getattr__(self,key):
        try:
            return self.database[self.name][key]
        except:
             raise AttributeError
    def __delattr__(self, key):
        del self.database[self.name][key]
    def give(self):
        "Yield an actionable job?"
        ids = []
        for branch in self.database[self.name]:
            br = self.database[self.name]['revs'][branch]
            ids = ids + [rev for rev in br if br[rev]['Builds'] == 0]
        return ids
    def lookup_vcs(self):
        "Which VCS does the build use?"
        d = self.database
        if self.name in d['vcs']:
            return d['vcs'][self.name]
        else:
            return "haikuports"
        #This is the VCS of the development/source of the package 
        #not of the software within
        #Gorram Brecht, we needed that parser for real beps.
    

if __name__ == '__main__':
    debug(True)
    try:
        with open('data.pkl', 'rb') as our_file:
            our_db = cPickle.load(our_file)
    except EOFError:
        our_db = {}
    atexit.register(close_pickle, our_db)
    run(host='192.168.1.45', port=8080, reloader=True)
Esempio n. 40
0
    def __init__(self, bikaApi, irodsApi):
        # Web service methods
        post('/bika/login')(bikaApi.login)
        post('/bika/get/clients')(bikaApi.get_clients)
        post('/bika/get/contacts')(bikaApi.get_contacts)
        post('/bika/get/samples')(bikaApi.get_samples)
        post('/bika/get/analysis_requests')(bikaApi.get_analysis_requests)
        post('/bika/get/arimports')(bikaApi.get_arimports)
        post('/bika/get/batches')(bikaApi.get_batches)
        post('/bika/get/worksheets')(bikaApi.get_worksheets)
        post('/bika/get/deliveries')(bikaApi.get_worksheets)
        post('/bika/get/invoices')(bikaApi.get_invoices)
        post('/bika/get/price_list')(bikaApi.get_price_list)
        post('/bika/get/supply_orders')(bikaApi.get_supply_orders)
        post('/bika/get/purchase_orders')(bikaApi.get_supply_orders)
        post('/bika/get/lab_products')(bikaApi.get_lab_products)
        post('/bika/get/storage_locations')(bikaApi.get_storage_locations)
        post('/bika/get/manufacturers')(bikaApi.get_manufacturers)
        post('/bika/get/suppliers')(bikaApi.get_suppliers)
        post('/bika/get/artemplates')(bikaApi.get_artemplates)
        post('/bika/get/analysis_profiles')(bikaApi.get_analysis_profiles)
        post('/bika/get/analysis_services')(bikaApi.get_analysis_services)
        post('/bika/get/sample_types')(bikaApi.get_sample_types)
        post('/bika/get/users')(bikaApi.get_users)
        post('/bika/get/manager_users')(bikaApi.get_manager_users)
        post('/bika/get/analyst_users')(bikaApi.get_analyst_users)
        post('/bika/get/clerk_users')(bikaApi.get_clerk_users)
        post('/bika/get/client_users')(bikaApi.get_client_users)

        post('/bika/set/analysis_result')(bikaApi.set_analysis_result)
        post('/bika/set/analyses_results')(bikaApi.set_analyses_results)

        post('/bika/update/batch')(bikaApi.update_batch)
        post('/bika/update/batches')(bikaApi.update_batches)
        post('/bika/update/analysis_request')(bikaApi.update_analysis_request)
        post('/bika/update/analysis_requests')(
            bikaApi.update_analysis_requests)
        post('/bika/update/worksheet')(bikaApi.update_worksheet)
        post('/bika/update/worksheets')(bikaApi.update_worksheets)
        post('/bika/update/delivery')(bikaApi.update_worksheet)
        post('/bika/update/deliveries')(bikaApi.update_worksheets)
        post('/bika/update/supply_order')(bikaApi.update_supply_order)
        post('/bika/update/supply_orders')(bikaApi.update_supply_orders)
        post('/bika/update/purchase_order')(bikaApi.update_supply_order)
        post('/bika/update/purchase_orders')(bikaApi.update_supply_orders)
        post('/bika/update/lab_product')(bikaApi.update_lab_product)
        post('/bika/update/lab_products')(bikaApi.update_lab_products)
        post('/bika/update/client')(bikaApi.update_client)
        post('/bika/update/clients')(bikaApi.update_clients)
        post('/bika/update/contact')(bikaApi.update_contact)
        post('/bika/update/contacts')(bikaApi.update_contacts)

        post('/bika/cancel/batch')(bikaApi.cancel_batch)
        post('/bika/cancel/worksheet')(bikaApi.update_worksheets)
        post('/bika/cancel/analysis_request')(bikaApi.cancel_analysis_request)
        post('/bika/reinstate/batch')(bikaApi.reinstate_batch)
        post('/bika/reinstate/worksheet')(bikaApi.update_worksheets)
        post('/bika/reinstate/analysis_request')(
            bikaApi.reinstate_analysis_request)

        post('/bika/action/receive_sample')(bikaApi.receive_sample)
        post('/bika/action/close_batch')(bikaApi.close_batch)
        post('/bika/action/open_batch')(bikaApi.open_batch)
        post('/bika/action/close_worksheet')(bikaApi.update_worksheets)
        post('/bika/action/open_worksheet')(bikaApi.update_worksheets)
        post('/bika/action/submit')(bikaApi.submit)
        post('/bika/action/verify')(bikaApi.verify)
        post('/bika/action/publish')(bikaApi.publish)
        post('/bika/action/republish')(bikaApi.republish)
        post('/bika/action/activate_supply_order')(
            bikaApi.activate_supply_order)
        post('/bika/action/deactivate_supply_order')(
            bikaApi.deactivate_supply_order)
        post('/bika/action/dispatch_supply_order')(
            bikaApi.dispatch_supply_order)
        post('/bika/action/activate_lab_product')(bikaApi.activate_lab_product)
        post('/bika/action/deactivate_lab_product')(
            bikaApi.deactivate_lab_product)
        post('/bika/action/activate_client')(bikaApi.activate_client)
        post('/bika/action/deactivate_client')(bikaApi.deactivate_client)

        post('/bika/create/client')(bikaApi.create_client)
        post('/bika/create/contact')(bikaApi.create_contact)
        post('/bika/create/batch')(bikaApi.create_batch)
        post('/bika/create/analysis_request')(bikaApi.create_analysis_request)
        post('/bika/create/worksheet')(bikaApi.create_worksheet)
        post('/bika/create/delivery')(bikaApi.create_worksheet)
        post('/bika/create/supply_order')(bikaApi.create_supply_order)
        post('/bika/create/purchase_order')(bikaApi.create_supply_order)
        post('/bika/create/lab_product')(bikaApi.create_lab_product)

        post('/bika/count/analysis_requests')(bikaApi.count_analysis_requests)
        post('/bika/count/samples')(bikaApi.count_samples)

        post('/irods/get/running')(irodsApi.get_running_folders)
        post('/irods/get/runs')(irodsApi.get_runs)
        post('/irods/check/runs')(irodsApi.check_runs)
        post('/irods/sync/batchbook')(irodsApi.sync_batchbook)
        post('/irods/put/samplesheet')(irodsApi.put_samplesheet)
        post('/irods/get/samplesheet')(irodsApi.get_samplesheet)
        post('/irods/cancel/samplesheet')(irodsApi.rm_samplesheet)

        # check status
        post('/web/check/status')(self.test_server)
        post('/bika/check/status')(bikaApi.test_server)
        post('/irods/check/status')(irodsApi.test_server)
Esempio n. 41
0
            update.body = body
            update.character_id = character_id
            update.chapter_id = chapter_id
            update.passage_order = passage_order
            update.soliloquy = soliloquy
        else:
            # create
            new_passage = Passage(body, character_id, chapter_id, passage_order, soliloquy)
            session.add(new_passage)

        session.commit()
        redirect('/passages/all')

    def view(self, id):
        """passage information"""
        session = dbengine.connect()

        passages = {}
        for passage in session.query(Passage).\
                filter(Passage.id==id).order_by(Passage.id.desc()):
            passages[passage.id] = passage

        return render('passages/view.html', {'passages': passages})

go = Passages()
route('/passages/all')(go.all)
route('/passages/create')(go.create)
route('/passages/edit/:id')(go.edit)
post('/passages/save')(go.save)
route('/passages/view/:id')(go.view)
Esempio n. 42
0
        characters = {}
        for row in session.query(Character).order_by(Character.id):
            characters[row.id] = db_object_to_dict(row)

        passages = {}
        for row in session.query(Passage).\
                filter(Passage.chapter_id==id).order_by(Passage.passage_order):
            row.body = '<br />'.join(row.body.splitlines())
            passages[row.id] = db_object_to_dict(row)

        cp = app.get_config()
        splash_images_url = cp.get('paths', 'splash_images_url')

        return render(
            'chapters/view.html', {
                'all_chapters': all_chapters,
                'chapters': chapters,
                'characters': characters,
                'passages': passages,
                'splash_images_url': splash_images_url
            })


go = Chapters()
route('/chapters/all')(go.all)
route('/chapters/create')(go.create)
route('/chapters/edit/:id')(go.edit)
route('/chapters/index')(go.index)
post('/chapters/save')(go.save)
route('/chapters/view/:id')(go.view)
Esempio n. 43
0
    print "Server logs will be saved to '%s'." % args.log
    print "A much nicer view of these logs can be accessed at 'http://localhost:%s/logs' though." % args.port
    print ""
    print "The real-time status of this benchmark can be viewed at 'http://localhost:%s/status' and" % args.port
    print "The final report, once complete, can be found at 'http://localhost:%s/report'." % args.port
    print "------------------------------------------------------------------------------------------------------------"
    s = Server(args.client_hostnames, args.benchmark_time, args.chunk_size,
               args.file_size, args.heartbeat_interval,
               args.monitoring_interval, args.port, args.log)

    # Initialize routes
    bottle.get("/")(s.main)
    bottle.get("/status")(s.status)
    bottle.get("/report")(s.report)
    bottle.get("/logs")(s.logs)
    bottle.get("/about")(s.about)
    bottle.route('/static/:file_path#.+#')(s.static)
    bottle.get("/favicon.ico")(s.get_favicon)

    bottle.post("/hello")(s.hello)
    bottle.post(HEARTBEAT_PATH)(s.client_heartbeat)
    bottle.post(START_PATH)(s.client_start)
    bottle.post(STOP_PATH)(s.client_stop)
    bottle.post(RESOURCES_PATH)(s.client_resources)
    bottle.post(ROLLOVER_PATH)(s.client_rollover)

    s.run_benchmarks()
    bottle.run(host='localhost', port=args.port, debug=True, quiet=True)
    s.client_thread.join()
Esempio n. 44
0
        session = dbengine.connect()

        locations = {}
        for row in session.query(Location).order_by(Location.id):
            locations[row.id] = db_object_to_dict(row)

        return render('locations/index.html', {'locations': locations})

    def view(self, id):
        """location information"""
        session = dbengine.connect()

        all_locations = {}
        for row in session.query(Location).order_by(Location.id.desc()):
            all_locations[row.id] = db_object_to_dict(row)

        locations = {}
        for location in session.query(Location).\
                filter(Location.id==id).order_by(Location.id.desc()):
            locations[location.id] = location

        return render('locations/view.html', {'all_locations': all_locations, 'locations': locations})

go = Locations()
route('/locations/all')(go.all)
route('/locations/create')(go.create)
route('/locations/edit/:id')(go.edit)
route('/locations/index')(go.index)
post('/locations/save')(go.save)
route('/locations/view/:id')(go.view)
Esempio n. 45
0
			return cli_output(device.set_state(state))
		except ValueError:
			return bottle.HTTPError(400, "Invalid state: %s" % (state,))
	_wrapped.__name__ = 'put_%s' % (device.get_name(),)
	return _wrapped
def rest_list_states(device):
	""" Inside an HTTP OPTIONS, list a device's acceptable inputs """
	def _wrapped(*args, **kwargs):
		bottle.response.content_type = 'text/plain'
		return '\n'.join(device.get_acceptable_states()) + '\n'
	_wrapped.__name__ = 'options_%s' % (device.get_name(),)
	return _wrapped
for device in DEVICES:
	path = '/' + device._state_path()
	bottle.get(path)(rest_get_state(device))
	bottle.post(path)(rest_set_state(device))  # openhab can only post
	bottle.put(path)(rest_set_state(device))
	bottle.route(path, method='OPTIONS')(rest_list_states(device))
	# check for subdevices
	for name,subdev in device.subdevices.items():
		subpath = '/' + subdev._state_path()
		bottle.get(subpath)(rest_get_state(subdev))
		bottle.post(subpath)(rest_set_state(subdev))  # openhab can only post
		bottle.put(subpath)(rest_set_state(subdev))
		bottle.route(subpath, method='OPTIONS')(rest_list_states(subdev))
	# save to index
	klass = device.get_class()
	name = device.get_name()
	klass_devices = device_list.get(klass, {})
	klass_devices[name] = device
	device_list[klass] = klass_devices