Exemplo n.º 1
0
def configure_bottle(supervisor):
    supervisor.app.install(bottle.JSONPlugin(json_dumps=json_dumps))
    bottle.debug(supervisor.config['app.debug'])
    bottle.BaseTemplate.defaults.update({
        'DEBUG':
        bottle.DEBUG,
        'request':
        bottle.request,
        'h':
        html,
        'esc':
        html_escape,
        'aesc':
        attr_escape,
        'th':
        template_helper,
        'url':
        supervisor.app.get_url,
        'csrf_tag':
        csrf.csrf_tag,
        '_':
        lambda x: x,
        'REDIRECT_DELAY':
        supervisor.config.get('app.redirect_delay', 5),
        'u':
        to_unicode,
    })
Exemplo n.º 2
0
def get_app(config):
    """
    Get a Bottle app instance with all the routes set-up.

    :return: The built bottle app.
    """
    get_session = database.init_db(config["database"], config["search_index"])

    app = bottle.default_app()
    app.install(DatabasePlugin(get_session))
    app.install(ConfigPlugin(config))
    app.config.setdefault("canister.log_level", logging.root.level)
    app.config.setdefault("canister.log_path", None)
    app.config.setdefault("canister.debug", False)
    app.install(canister.Canister())
    # Use DateAwareJSONEncoder to dump JSON strings
    # From http://stackoverflow.com/questions/21282040/bottle-framework-how-to-return-datetime-in-json-response#comment55718456_21282666.  pylint: disable=locally-disabled,line-too-long
    bottle.install(
        bottle.JSONPlugin(
            json_dumps=functools.partial(json.dumps, cls=DateAwareJSONEncoder)
        )
    )

    # API v1 routes
    app.route("/api/v1/", "GET", api_routes.index_v1)

    app.route("/api/v1/time_to_places", "GET",
              api_routes.time_to_places_v1)

    app.route("/api/v1/flats", "GET", api_routes.flats_v1)
    app.route("/api/v1/flats/status/:status", "GET",
              api_routes.flats_by_status_v1)

    app.route("/api/v1/flat/:flat_id", "GET", api_routes.flat_v1)
    app.route("/api/v1/flat/:flat_id/status", "POST",
              api_routes.update_flat_status_v1)
    app.route("/api/v1/flat/:flat_id/notes", "POST",
              api_routes.update_flat_notes_v1)
    app.route("/api/v1/flat/:flat_id/notation", "POST",
              api_routes.update_flat_notation_v1)

    app.route("/api/v1/search", "POST", api_routes.search_v1)

    # Index
    app.route("/", "GET", lambda: _serve_static_file("index.html"))

    # Static files
    app.route("/favicon.ico", "GET",
              lambda: _serve_static_file("favicon.ico"))
    app.route(
        "/assets/<filename:path>", "GET",
        lambda filename: _serve_static_file("/assets/{}".format(filename))
    )
    app.route(
        "/img/<filename:path>", "GET",
        lambda filename: _serve_static_file("/img/{}".format(filename))
    )

    return app
Exemplo n.º 3
0
def init():
    db.connect()
    db.create_tables([Report])
    if not db.is_closed():
        db.close()

    # Use DateAwareJSONEncoder to dump JSON strings
    # From http://stackoverflow.com/questions/21282040/bottle-framework-how-to-return-datetime-in-json-response#comment55718456_21282666.  pylint: disable=locally-disabled,line-too-long
    bottle.install(
        bottle.JSONPlugin(json_dumps=functools.partial(
            json.dumps, cls=DateAwareJSONEncoder)))
Exemplo n.º 4
0
    def __init__(
        self,
        mongo_host=None,
        mongo_port=None,
        mongo_replica_set=None,
        emailer=None,
        metrics=None,
    ):
        super().__init__()
        self.__mongo = mongo_connection(mongo_host=mongo_host,
                                        mongo_port=mongo_port,
                                        mongo_replica_set=mongo_replica_set)
        self.__boulders = {}
        api.register(self)
        self.__emailer = emailer
        self.__metrics = metrics

        def json_bson_dumps(body):
            import bson.json_util
            return bottle.json_dumps(body, default=bson.json_util.default)

        self.install(bottle.JSONPlugin(json_bson_dumps))
Exemplo n.º 5
0
Gary Bishop May 2020
"""

import bottle
from bottle import view
from db import with_db, insert
import json
import os.path as osp
from datetime import datetime


# startup bottle
# allow returning datetime objects in json
app = application = bottle.Bottle(autojson=False)
app.install(bottle.JSONPlugin(json_dumps=lambda s: json.dumps(s, default=str)))


# make get_url available in all templates
def get_url(name, user=None, **kwargs):
    """get_url for use from templates"""
    url = app.get_url(name, **kwargs)
    return url


bottle.SimpleTemplate.defaults["get_url"] = get_url


def allow_json(func):
    """ Decorator: renders as json if requested """
Exemplo n.º 6
0
log = logging.getLogger("detector")
metrics = setup_metrics(name="detector")

db_conn = None  # Set by detector.py or during functional testing

asn_db = None  # Set by detector.py

def _datetime_handler(x):
    if isinstance(x, datetime):
        return x.isoformat()
    raise TypeError("unknown type")


bottle.install(
    bottle.JSONPlugin(json_dumps=lambda o: json.dumps(o, default=_datetime_handler))
)


def generate_chart(start_d, end_d, msmts, changes, title):
    """Render measurements and changes into a SVG chart
    :returns: dict
    """
    assert isinstance(msmts[0][0], datetime)
    x1 = 100
    x2 = 1100
    y1 = 50
    y2 = 300
    # scale x
    delta = (end_d - start_d).total_seconds()
    assert delta != 0
Exemplo n.º 7
0
# app is for campability for gunicorn
app = bottle.default_app()
# application is for compability for uwsgi
application = app

class AvroEncoder(json.JSONEncoder):
  def default(self, obj):
    if isinstance(obj, bytes):
      try:
        return obj.decode('utf8')
      except:
        return obj.decode('base64')
    return json.JSONEncoder.default(self, obj)

app.install(
    bottle.JSONPlugin(json_dumps=lambda s: json.dumps(s, cls=AvroEncoder))
)

@app.post('/avro/decode')
def decode_evh_capture():
  #import pdb;pdb.set_trace()
  reader = fastavro.reader(request.body)
  ret = []
  for l in reader:
    ret.append(l)
  return {'content': ret}


if __name__ == "__main__":
  app.run(host='localhost', port=8080, reloader=True)
Exemplo n.º 8
0
from BroControl import version
from BroControl.ser import dumps
import os
import bottle
import json

app = bottle.Bottle(autojson=False)
app.install(
    bottle.JSONPlugin(json_dumps=lambda s: json.dumps(s, default=dumps)))


@app.route('/start')
def start():
    i = app.daemon.call("start")
    return {"id": i}


@app.route('/stop')
def start():
    i = app.daemon.call("stop")
    return {"id": i}


@app.route('/restart')
def restart():
    i = app.daemon.call("restart")
    return {"id": i}


@app.route('/nodes')
def nodes():
Exemplo n.º 9
0
def main():
    bottle.install(
        bottle.JSONPlugin(
            json_dumps=lambda s: json.dumps(s, cls=CustomJsonEncoder)))
    bottle.run(host='0.0.0.0', port=8888, server='gevent')
Exemplo n.º 10
0
 def __init__(self, app):
     app.install(
         bottle.JSONPlugin(
             json_dumps=lambda s: json.dumps(s, cls=JsonDatetimeZEncoder)))
     self.app = app
Exemplo n.º 11
0
    def __init__(self, robot, host='localhost', port=8080):
        AbstractServer.__init__(self, robot)

        self.host = host
        self.port = port

        self.app = bottle.Bottle()
        self.app.install(
            bottle.JSONPlugin(
                json_dumps=lambda s: json.dumps(s, cls=self.json_encoder)))

        @self.app.get('/motor/list.json')
        def get_motor_list():
            req = {
                'get': {
                    '': [
                        'motors',
                    ]
                }
            }

            return self.request_handler.handle_request(req)['get']['']

        @self.app.get('/primitive/list.json')
        def get_primitive_list():
            req = {
                'get': {
                    '': [
                        'attached_primitives_name',
                    ]
                }
            }
            return self.request_handler.handle_request(req)['get']['']

        @self.app.get('/<name>/register.json')
        @self.app.get('/motor/<name>/register.json')
        def get_motor_register(name):
            req = {
                'get': {
                    name: [
                        'registers',
                    ]
                }
            }
            return self.request_handler.handle_request(req)['get'][name]

        @self.app.get('/<name>/<register>')
        @self.app.get('/motor/<name>/<register>')
        def get_object_register(name, register):
            req = {
                'get': {
                    name: [
                        register,
                    ]
                }
            }

            return self.request_handler.handle_request(req)['get'][name]

        @self.app.post('/<name>/<register>')
        @self.app.post('/motor/<name>/<register>')
        def set_object_register(name, register):
            req = {'set': {name: {register: bottle.request.json}}}

            return self.request_handler.handle_request(req)

        @self.app.post('/<prim_name>/call/<meth_name>')
        @self.app.post('/primitive/<prim_name>/call/<meth_name>')
        def call_prim_meth(prim_name, meth_name):
            req = {'call': {prim_name: {meth_name: bottle.request.json}}}
            return self.request_handler.handle_request(req)['call'][prim_name]

        @self.app.post('/request.json')
        def request():
            return self.request_handler.handle_request(bottle.request.json)

        logger.info('Starting HTTPServer on http://%s:%s', host, port)
Exemplo n.º 12
0
        try:
            body = callback(session, *args, **kwargs)
        except sqlalchemy.exc.SQLAlchemyError as exc:
            session.rollback()
            raise bottle.HTTPError(500, "A database error occurred.", exc)
        finally:
            session.close()

        return body

    return wrapper


app.install(create_sqlalchemy_session)
app.install(bottle.JSONPlugin())


def send_bytes(bytes_, mimetype):
    """Bottle method for sending bytes objects."""
    headers = dict()
    headers["Content-Type"] = mimetype
    headers["Content-Length"] = len(bytes_)

    body = "" if bottle.request.method == "HEAD" else bytes_
    return bottle.HTTPResponse(body, **headers)


##################
# Error handling #
##################
Exemplo n.º 13
0
    def __init__(self, robot, host, port):
        AbstractServer.__init__(self, robot, host, port)

        self.app = bottle.Bottle()

        jd = lambda s: json.dumps(s, cls=MyJSONEncoder)
        self.app.install(bottle.JSONPlugin(json_dumps=jd))

        rr = self.restfull_robot

        # Motors route

        @self.app.get('/motor/list.json')
        @self.app.get('/motor/<alias>/list.json')
        def get_motor_list(alias='motors'):
            return {alias: rr.get_motors_list(alias)}

        @self.app.get('/sensor/list.json')
        def get_sensor_list():
            return {'sensors': rr.get_sensors_list()}

        @self.app.get('/motor/alias/list.json')
        def get_motor_alias():
            return {'alias': rr.get_motors_alias()}

        @self.app.get('/motor/<motor_name>/register/list.json')
        @self.app.get('/sensor/<motor_name>/register/list.json')
        def get_motor_registers(motor_name):
            return {'registers': rr.get_motor_registers_list(motor_name)}

        @self.app.get('/motor/<motor_name>/register/<register_name>')
        @self.app.get('/sensor/<motor_name>/register/<register_name>')
        def get_register_value(motor_name, register_name):
            return {
                register_name:
                rr.get_motor_register_value(motor_name, register_name)
            }

        @self.app.post(
            '/motor/<motor_name>/register/<register_name>/value.json')
        @self.app.post(
            '/sensor/<motor_name>/register/<register_name>/value.json')
        def set_register_value(motor_name, register_name):
            rr.set_motor_register_value(motor_name, register_name,
                                        bottle.request.json)
            return {}

        # Sensors route

        # Primitives route
        @self.app.get('/primitive/list.json')
        def get_primitives_list(self):
            return {'primitives': rr.get_primitives_list()}

        @self.app.get('/primitive/running/list.json')
        def get_running_primitives_list(self):
            return {'running_primitives': rr.get_running_primitives_list()}

        @self.app.get('/primitive/<prim>/start.json')
        def start_primitive(self, prim):
            rr.start_primitive(prim)

        @self.app.get('/primitive/<prim>/stop.json')
        def stop_primitive(self, prim):
            rr.stop_primitive(prim)

        @self.app.get('/primitive/<prim>/pause.json')
        def pause_primitive(self, prim):
            rr.pause_primitive(prim)

        @self.app.get('/primitive/<prim>/resume.json')
        def resume_primitive(self, prim):
            rr.resume_primitive(prim)

        @self.app.get('/primitive/<prim>/property/list.json')
        def get_primitive_properties_list(self, prim):
            return {'property': rr.get_primitive_properties_list(prim)}

        @self.app.get('/primitive/<prim>/property/<prop>')
        def get_primitive_property(self, prim, prop):
            res = rr.get_primitive_property(prim, prop)
            return {'{}.{}'.format(prim, prop): res}

        @self.app.post('/primitive/<prim>/property/<prop>/value.json')
        def set_primitive_property(self, prim, prop):
            rr.set_primitive_property(prim, prop, bottle.request.json)

        @self.app.get('/primitive/<prim>/method/list.json')
        def get_primitive_methods_list(self, prim):
            return {'methods': rr.get_primitive_methods_list(self, prim)}

        @self.app.post('/primitive/<prim>/method/<meth>/args.json')
        def call_primitive_method(self, prim, meth):
            res = rr.call_primitive_method(prim, meth, bottle.request.json)
            return {'{}:{}'.format(prim, meth): res}
Exemplo n.º 14
0
def registra_plugins():
    from bottle_cerberus import CerberusPlugin
    bottle.install(CerberusPlugin())
    bottle.install(bottle.JSONPlugin(json_dumps=lambda s: simplejson.dumps(s, cls=CustomEncoder)))
Exemplo n.º 15
0
import bottle
from bottle import route
# from bottle.ext import sqlalchemy
import bottle.ext.sqlalchemy
import latci.database
import functools

from latci import config
import latci.json

application = bottle.app()
application.uninstall(bottle.JSONPlugin)
application.install(bottle.JSONPlugin(json_dumps=functools.partial(latci.json.dumps, indent=True)))

# Install SQLAlchemy plguin
application.install(
    bottle.ext.sqlalchemy.Plugin(
        latci.database.engine, # SQLAlchemy engine created with create_engine function.
        None, # SQLAlchemy metadata, required only if create=True.
        keyword='db', # Keyword used to inject session database in a route (default 'db').
        create=False, # If it is true, execute `metadata.create_all(engine)` when plugin is applied (default False).
        commit=False, # If it is true, plugin commit changes after route is executed (default True).
        use_kwargs=True # If it is true and keyword is not defined, plugin uses **kwargs argument to inject session database (default False).
    )
)


# Required for proper initialization of routes.  Can't be before bottle.app() calls.
import latci.views

Exemplo n.º 16
0
from pyethereum.chainmanager import chain_manager
from pyethereum.peermanager import peer_manager
import pyethereum.dispatch as dispatch
from pyethereum.blocks import block_structure, Block
import pyethereum.signals as signals
from pyethereum.transactions import Transaction
import pyethereum.processblock as processblock
import pyethereum.utils as utils
import pyethereum.rlp as rlp
from ._version import get_versions

logger = logging.getLogger(__name__)

app = bottle.Bottle()
app.config['autojson'] = False
app.install(bottle.JSONPlugin(json_dumps=lambda s: json.dumps(s, sort_keys=True)))


class ApiServer(threading.Thread):

    def __init__(self):
        super(ApiServer, self).__init__()
        self.daemon = True
        self.listen_host = '127.0.0.1'
        self.port = 30203

    def configure(self, config):
        self.listen_host = config.get('api', 'listen_host')
        self.port = config.getint('api', 'listen_port')
        # add api_path to bottle to be used in the middleware
        api_path = config.get('api', 'api_path')
Exemplo n.º 17
0
    def __init__(self, robot, host='localhost', port=8080):
        AbstractServer.__init__(self, robot)

        self.host = host
        self.port = port

        self.app = bottle.Bottle()
        self.app.install(
            bottle.JSONPlugin(
                json_dumps=lambda s: json.dumps(s, cls=MyJSONEncoder)))

        #test index
        # @self.app.get('/')
        # def index(name='test'):
        #     # return bottle.template('<b>Hello {{name}}</b>!', name=name)
        #     idx = '/home/steve/Project/Repo/poppy-software/example/web/'
        #     return bottle.static_file('/',root = idx )

        # test index
        @self.app.get('/<filename>')
        def index_static(filename):
            # return bottle.template('<b>Hello {{name}}</b>!', name=name)
            path = '/home/steve/Project/Repo/poppy-software/example/web/'
            return bottle.static_file(filename, root=path)

        @self.app.get('/flot/<filename>')
        def index_static(filename):
            # return bottle.template('<b>Hello {{name}}</b>!', name=name)
            path = '/home/steve/Project/Repo/poppy-software/example/web/flot/'
            return bottle.static_file(filename, root=path)

        @self.app.get('/motor/list.json')
        def get_motor_list():
            req = {
                'get': {
                    '': [
                        'motors',
                    ]
                }
            }

            return self.request_handler.handle_request(req)['get']['']

        @self.app.get('/primitive/list.json')
        def get_primitive_list():
            req = {
                'get': {
                    '': [
                        'attached_primitives_name',
                    ]
                }
            }
            return self.request_handler.handle_request(req)['get']['']

        @self.app.get('/<name>/register.json')
        @self.app.get('/motor/<name>/register.json')
        def get_motor_register(name):
            req = {
                'get': {
                    name: [
                        'registers',
                    ]
                }
            }
            return self.request_handler.handle_request(req)['get'][name]

        @self.app.get('/<name>/<register>')
        @self.app.get('/motor/<name>/<register>')
        def get_object_register(name, register):
            req = {
                'get': {
                    name: [
                        register,
                    ]
                }
            }

            return self.request_handler.handle_request(req)['get'][name]

        @self.app.post('/<name>/<register>')
        @self.app.post('/motor/<name>/<register>')
        def set_object_register(name, register):
            req = {'set': {name: {register: bottle.request.json}}}

            return self.request_handler.handle_request(req)

        @self.app.post('/<prim_name>/call/<meth_name>')
        @self.app.post('/primitive/<prim_name>/call/<meth_name>')
        def call_prim_meth(prim_name, meth_name):
            req = {'call': {prim_name: {meth_name: bottle.request.json}}}
            return self.request_handler.handle_request(req)['call'][prim_name]

        @self.app.post('/request.json')
        def request():
            return self.request_handler.handle_request(bottle.request.json)

        logger.info('Starting HTTPServer on http://%s:%s', host, port)
Exemplo n.º 18
0

class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, model.Abstract):
            value = o.pack()
        elif isinstance(o, uuid.UUID):
            value = str(o)
        else:
            value = super().default(o)
        return value


app = bottle.Bottle(autojson=False)
app.install(
    bottle.JSONPlugin(
        json_dumps=functools.partial(json.dumps, cls=JSONEncoder)))
config_key = 'traffexam.{}'.format


@app.route('/address', methpd='GET')
def address_list():
    context = get_context()
    return address_response(context.service.address.list())


@app.route('/address', method='POST')
def address_create():
    context = get_context()

    payload = bottle.request.json
    payload.pop('idnr', None)
Exemplo n.º 19
0
    get_related_posts,
    payouts_total,
    payouts_last_24h,
)


logger = logging.getLogger(__name__)

app = bottle.Bottle()
app.config['hive.MAX_BLOCK_NUM_DIFF'] = 10
app.config['hive.MAX_DB_ROW_RESULTS'] = 100000
app.config['hive.DB_QUERY_LIMIT'] = app.config['hive.MAX_DB_ROW_RESULTS'] + 1
app.config['hive.logger'] = logger

app.install(
    bottle.JSONPlugin(json_dumps=lambda s: json.dumps(s, cls=ToStringJSONEncoder)))
app.install(ErrorsRestPlugin())


# Non JSON-RPC routes
# -------------------
@app.get('/health')
def health():
    state = db_head_state()
    if state['db_head_age'] > app.config['hive.MAX_BLOCK_NUM_DIFF'] * 3:
        abort(
            500,
            'head block age (%ss) > max allowable (%ss); head block num: %s'
            % (state['db_head_age'], app.config['hive.MAX_BLOCK_NUM_DIFF'] * 3,
                state['db_head_block']))
    else:
Exemplo n.º 20
0
def get_app(config):
    """
    Get a Bottle app instance with all the routes set-up.

    :return: The built bottle app.
    """
    get_session = database.init_db(config["database"], config["search_index"])

    app = bottle.Bottle()
    app.install(DatabasePlugin(get_session))
    app.install(ConfigPlugin(config))
    app.config.setdefault("canister.log_level", "DISABLED")
    app.config.setdefault("canister.log_path", False)
    app.config.setdefault("canister.debug", False)
    app.install(canister.Canister())
    # Use DateAwareJSONEncoder to dump JSON strings
    # From http://stackoverflow.com/questions/21282040/bottle-framework-how-to-return-datetime-in-json-response#comment55718456_21282666.  pylint: disable=locally-disabled,line-too-long
    app.install(
        bottle.JSONPlugin(json_dumps=functools.partial(
            json.dumps, cls=DateAwareJSONEncoder)))

    # Enable CORS
    @app.hook("after_request")
    def enable_cors():
        """
        Add CORS headers at each request.
        """
        # The str() call is required as we import unicode_literal and WSGI
        # headers list should have plain str type.
        bottle.response.headers[str("Access-Control-Allow-Origin")] = str("*")
        bottle.response.headers[str("Access-Control-Allow-Methods")] = str(
            "PUT, GET, POST, DELETE, OPTIONS, PATCH")
        bottle.response.headers[str("Access-Control-Allow-Headers")] = str(
            "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token")

    # API v1 routes
    app.route("/api/v1", ["GET", "OPTIONS"], api_routes.index_v1)

    app.route("/api/v1/time_to_places", ["GET", "OPTIONS"],
              api_routes.time_to_places_v1)

    app.route("/api/v1/flats", ["GET", "OPTIONS"], api_routes.flats_v1)
    app.route("/api/v1/flats/:flat_id", ["GET", "OPTIONS"], api_routes.flat_v1)
    app.route("/api/v1/flats/:flat_id", ["PATCH", "OPTIONS"],
              api_routes.update_flat_v1)

    app.route("/api/v1/ics/visits.ics", ["GET", "OPTIONS"],
              api_routes.ics_feed_v1)

    app.route("/api/v1/search", ["POST", "OPTIONS"], api_routes.search_v1)

    app.route("/api/v1/opendata", ["GET", "OPTIONS"],
              api_routes.opendata_index_v1)
    app.route(
        "/api/v1/opendata/postal_codes",
        ["GET", "OPTIONS"],
        api_routes.opendata_postal_codes_v1,
    )

    app.route("/api/v1/metadata", ["GET", "OPTIONS"], api_routes.metadata_v1)
    app.route("/api/v1/import", ["GET", "OPTIONS"], api_routes.import_v1)

    # Index
    app.route("/", "GET", lambda: _serve_static_file("index.html"))

    # Static files
    app.route("/favicon.ico", "GET", lambda: _serve_static_file("favicon.ico"))
    app.route(
        "/assets/<filename:path>",
        "GET",
        lambda filename: _serve_static_file("/assets/{}".format(filename)),
    )
    app.route(
        "/img/<filename:path>",
        "GET",
        lambda filename: _serve_static_file("/img/{}".format(filename)),
    )
    app.route(
        "/.well-known/<filename:path>",
        "GET",
        lambda filename: _serve_static_file("/.well-known/{}".format(filename)
                                            ),
    )
    app.route(
        "/data/img/<filename:path>",
        "GET",
        lambda filename: bottle.static_file(
            filename, root=os.path.join(config["data_directory"], "images")),
    )

    return app
Exemplo n.º 21
0
def start_adminpanel(zigate_instance,
                     port=ADMINPANEL_PORT,
                     mount=None,
                     prefix=None,
                     autostart=True,
                     daemon=True,
                     quiet=True,
                     debug=False):
    '''
    mount: url prefix used to mount bottle application
    prefix: special prefix added when using get_url in template, eg proxy.php
    '''
    app = bottle.Bottle()
    app.install(
        bottle.JSONPlugin(json_dumps=lambda s: dumps(s, cls=DeviceEncoder)))

    def get_url(routename, **kwargs):
        '''
        customized get_url to allow additional prefix args
        '''
        redirect = kwargs.pop('redirect', False)
        scriptname = bottle.request.environ.get('SCRIPT_NAME',
                                                '').strip('/') + '/'
        location = app.router.build(routename, **kwargs).lstrip('/')
        url = bottle.urljoin(bottle.urljoin('/', scriptname), location)
        if prefix and not redirect:
            url = prefix + '?' + bottle.urlencode({'q': url})
        append = '?'
        if '?' in url:
            append = '&'
        url += '{}_={}'.format(append, time.time())
        return url

    def redirect(routename, **kwargs):
        '''
        convenient function to redirect using routename instead of url
        '''
        return bottle.redirect(get_url(routename, redirect=True, **kwargs))

    bottle.BaseTemplate.defaults['get_url'] = get_url
    bottle.BaseTemplate.defaults['zigate'] = zigate_instance
    app.zigate = zigate_instance

    @app.route('/', name='index')
    @bottle.view('index')
    def index():
        connected = zigate_instance.connection and zigate_instance.connection.is_connected(
        )

        grouped_devices = {}
        processed = []

        def add_device_to_group(group, addr, endpoint=''):
            name = 'Missing'
            last_seen = ''
            if addr == zigate_instance.addr:
                name = 'ZiGate'
            zdev = zigate_instance.get_device_from_addr(addr)
            if zdev:
                name = str(zdev)
                last_seen = zdev.info.get('last_seen', '')
            else:
                name = '{} ({})'.format(name, addr)
            group.append({
                'addr': addr,
                'endpoint': endpoint,
                'name': name,
                'last_seen': last_seen
            })

        for group, group_devices in zigate_instance.groups.items():
            grouped_devices[group] = []
            for device in group_devices:
                addr = device[0]
                endpoint = device[1]
                processed.append(addr)
                add_device_to_group(grouped_devices[group], addr, endpoint)

        grouped_devices[''] = []
        for device in zigate_instance.devices:
            if device.addr not in processed:
                add_device_to_group(grouped_devices[''], device.addr)

        port = zigate_instance._port or 'auto'
        if hasattr(zigate_instance, '_host'):
            port = '{}:{}'.format(zigate_instance._host, port)

        return {
            'libversion': zigate_version.__version__,
            'port': port,
            'connected': connected,
            'version': zigate_instance.get_version_text(),
            'model': zigate_instance.model,
            'groups': zigate_instance.groups,
            'grouped_devices': grouped_devices,
        }

    @app.route('/networkmap', name='networkmap')
    @bottle.view('networkmap')
    def networkmap():
        return

    @app.route('/device/<addr>', name='device')
    @bottle.view('device')
    def device(addr):
        device = zigate_instance.get_device_from_addr(addr)
        if not device:
            return redirect('index')
        return {'device': device}

    @app.route('/api/permit_join', name='api_permit_join')
    def permit_join():
        zigate_instance.permit_join()
        return redirect('index')

    @app.route('/api/led', name='api_led')
    def set_led():
        on = bottle.request.query.get('on', 'true') == 'true'
        zigate_instance.set_led(on)
        return redirect('index')

    @app.route('/api/discover/<addr>', name='api_discover')
    def api_discover(addr):
        zigate_instance.discover_device(addr, True)
        return redirect('device', addr=addr)

    @app.route('/api/refresh/<addr>', name='api_refresh')
    def api_refresh(addr):
        zigate_instance.refresh_device(addr)
        return redirect('device', addr=addr)

    @app.route('/api/remove/<addr>', name='api_remove')
    def api_remove(addr):
        force = bottle.request.query.get('force', 'false') == 'true'
        zigate_instance.remove_device(addr, force)
        return redirect('index')

    @app.route('/device/<addr>/save',
               name='device_save',
               method=['GET', 'POST'])
    def device_save(addr):
        device = zigate_instance.get_device_from_addr(addr)
        if not device:
            return redirect('index')
        device.name = bottle.request.forms.name
        return redirect('device', addr=addr)

    @app.route('/api/devices', name='api_devices')
    def devices():
        devices = [{
            'info': {
                'addr': zigate_instance.addr,
                'ieee': zigate_instance.ieee
            },
            'friendly_name': 'ZiGate'
        }]
        for d in zigate_instance.devices:
            device = d.to_json()
            device['friendly_name'] = str(d)
            devices.append(device)
        return {'devices': devices}

    @app.route('/api/network_table', name='api_network_table')
    def network_table():
        force = bottle.request.query.get('force', 'false') == 'true'
        return {'network_table': zigate_instance.build_neighbours_table(force)}

    kwargs = {'host': '0.0.0.0', 'port': port, 'quiet': quiet, 'debug': debug}

    if autostart:
        r_app = app
        if mount:
            root_app = bottle.Bottle()
            root_app.mount(mount, app)
            r_app = root_app
        if daemon:
            t = threading.Thread(target=r_app.run, kwargs=kwargs, daemon=True)
            t.start()
        else:
            r_app.run(**kwargs)
    return app
Exemplo n.º 22
0
    def __init__(self, robot, host='0.0.0.0', port='8080', cross_domain_origin='*', quiet=True):
        AbstractServer.__init__(self, robot, host, port)
        self.quiet = quiet
        self.app = bottle.Bottle()

        jd = lambda s: json.dumps(s, cls=MyJSONEncoder)
        self.app.install(bottle.JSONPlugin(json_dumps=jd))

        if(cross_domain_origin):
            self.app.install(EnableCors(cross_domain_origin))

        rr = self.restfull_robot

        @self.app.route("/", method=['OPTIONS'])
        @self.app.route("/<p:path>", method=['OPTIONS'])
        def options(p=""):
            return ""

        # Motors route
        @self.app.get('/')
        @self.app.get('/robot.json')
        def robot():
            out = {
                'motors': [],
                'primitives': []
            }
            for m in rr.get_motors_list('motors'):
                motor = {}
                for r in rr.get_motor_registers_list(m):
                    try:
                        motor[r] = rr.get_motor_register_value(m, r)
                    except AttributeError:
                        pass
                out['motors'].append(motor)

            running_primitives = rr.get_running_primitives_list()
            for prim in rr.get_primitives_list():
                primitve = {'primitive': prim,
                            'running': prim in running_primitives,
                            'properties': [],
                            'methods': rr.get_primitive_methods_list(prim)
                            }
                for prop in rr.get_primitive_properties_list(prim):
                    primitve['properties'].append({'property': prop, 'value': rr.get_primitive_property(prim, prop)})
                out['primitives'].append(primitve)

            return out

        @self.app.get('/motor/list.json')
        @self.app.get('/motor/<alias>/list.json')
        def get_motor_list(alias='motors'):
            return {
                alias: rr.get_motors_list(alias)
            }

        @self.app.get('/sensor/list.json')
        def get_sensor_list():
            return {
                'sensors': rr.get_sensors_list()
            }

        @self.app.get('/motor/alias/list.json')
        def get_motor_alias():
            return {
                'alias': rr.get_motors_alias()
            }

        @self.app.get('/motor/<motor_name>/register/list.json')
        @self.app.get('/sensor/<motor_name>/register/list.json')
        def get_motor_registers(motor_name):
            return {
                'registers': rr.get_motor_registers_list(motor_name)
            }

        @self.app.get('/motor/<motor_name>/register/<register_name>')
        @self.app.get('/sensor/<motor_name>/register/<register_name>')
        def get_register_value(motor_name, register_name):
            return {
                register_name: rr.get_motor_register_value(motor_name, register_name)
            }

        @self.app.post('/motor/<motor_name>/register/<register_name>/value.json')
        @self.app.post('/sensor/<motor_name>/register/<register_name>/value.json')
        def set_register_value(motor_name, register_name):
            rr.set_motor_register_value(motor_name, register_name,
                                        bottle.request.json)
            return {}

        # Sensors route

        # Primitives route
        @self.app.get('/primitive/list.json')
        def get_primitives_list():
            return {
                'primitives': rr.get_primitives_list()
            }

        @self.app.get('/primitive/running/list.json')
        def get_running_primitives_list():
            return {
                'running_primitives': rr.get_running_primitives_list()
            }

        @self.app.get('/primitive/<prim>/start.json')
        def start_primitive(prim):
            rr.start_primitive(prim)

        @self.app.get('/primitive/<prim>/stop.json')
        def stop_primitive(prim):
            rr.stop_primitive(prim)

        @self.app.get('/primitive/<prim>/pause.json')
        def pause_primitive(prim):
            rr.pause_primitive(prim)

        @self.app.get('/primitive/<prim>/resume.json')
        def resume_primitive(prim):
            rr.resume_primitive(prim)

        @self.app.get('/primitive/<prim>/property/list.json')
        def get_primitive_properties_list(prim):
            return {
                'property': rr.get_primitive_properties_list(prim)
            }

        @self.app.get('/primitive/<prim>/property/<prop>')
        def get_primitive_property(prim, prop):
            res = rr.get_primitive_property(prim, prop)
            return {
                '{}.{}'.format(prim, prop): res
            }

        @self.app.post('/primitive/<prim>/property/<prop>/value.json')
        def set_primitive_property(prim, prop):
            rr.set_primitive_property(prim, prop,
                                      bottle.request.json)

        @self.app.get('/primitive/<prim>/method/list.json')
        def get_primitive_methods_list(prim):
            return {
                'methods': rr.get_primitive_methods_list(self, prim)
            }

        @self.app.post('/primitive/<prim>/method/<meth>/args.json')
        def call_primitive_method(prim, meth):
            res = rr.call_primitive_method(prim, meth,
                                           bottle.request.json)
            return {
                '{}:{}'.format(prim, meth): res
            }

        @self.app.get('/motors/register/<register_name>')
        def get_motors_register_value(register_name):
            motors_list = rr.get_motors_list('motors')
            registers_motors = {}

            for motor_name in motors_list:
                registers_motors[motor_name] = {
                    register_name: rr.get_motor_register_value(motor_name, register_name)
                }

            return registers_motors
Exemplo n.º 23
0
#

import collections
import functools
import json
import multiprocessing.pool
import uuid
from wsgiref.simple_server import WSGIServer, WSGIRequestHandler

import bottle

from kilda.traffexam import exc
from kilda.traffexam import model

app = bottle.Bottle(autojson=False)
app.install(bottle.JSONPlugin(
        json_dumps=functools.partial(json.dumps, cls=model.JSONEncoder)))
config_key = 'traffexam.{}'.format


@app.route('/address', methpd='GET')
def address_list():
    context = get_context()
    return address_response(context.service.address.list())


@app.route('/address', method='POST')
def address_create():
    context = get_context()

    payload = bottle.request.json
    payload.pop('idnr', None)