Example #1
0
def Application():
	app = Bottle()
	app.catchall = False
	# tasks
	@app.route('/task',method='POST')
	def post_task():
		return {'result':False}
	@app.route('/task/:uid',method='GET')
	def get_task(uid):
		return {}
	# solutions
	@app.route('/solution',method='POST')
	def post_solution():
		return {'result':False}
	@app.route('/solution/:uid',method='GET')
	def get_solution(uid):
		return {}
	# votes
	@app.route('/vote',method='POST')
	def post_vote():
		return {'result':False}
	# static files
	@app.route('/')
	def http_index():
		return static_file('index.htm',root='./www')
	@app.route('/:path#.+#')
	def http_static(path):
		return static_file(path,root='./www')
	return app
Example #2
0
class WebService:

    def __init__(self, event_manager):

        self._event_manager = event_manager
        self._event_manager.register_event('on_porta_unlock_request')

        self._webservice = Bottle()
        self._setup_routing()


    def _setup_routing(self):
        self._webservice.route('/fablab/porta/<action>', method="GET", callback=self._manage_porta)
        

    def get_status(self):

        # restituisce informazioni su quale sia lo status del servizio
        # in modo strutturato (verra' tramutato in json)

        pass


    def start(self, host='0.0.0.0', port=8080):
        self._host = host
        self._port = port
        self._webservice.run( host=self._host, port=self._port )


    def _manage_porta(self, action):
        if action == 'unlock':
            self._event_manager.trigger_event('on_porta_unlock_request', self)
Example #3
0
    def __init__(self, name, address="0.0.0.0", port=8080, keyfile=None, certfile=None, routes_config=None, send_errors=False, use_response_wrapper=True, *args, **kwargs):
        Actor.__init__(self, name, *args, **kwargs)
        Bottle.__init__(self)
        self.blockdiag_config["shape"] = "cloud"
        self.address = address
        self.port = port
        self.keyfile = keyfile
        self.certfile = certfile
        self.responders = {}
        self.send_errors = send_errors
        self.use_response_wrapper = use_response_wrapper
        routes_config = routes_config or self.DEFAULT_ROUTE

        if isinstance(routes_config, str):
            routes_config = json.loads(routes_config)

        if isinstance(routes_config, dict):
            named_routes = {route['id']:{'path': route['path'], 'base_path': route.get('base_path', None)} for route in routes_config.get('routes') if route.get('id', None)}
            for route in routes_config.get('routes'):
                callback = getattr(self, route.get('callback', 'callback'))
                if route.get('base_path', None):
                    route['path'] = self.combine_base_paths(route, named_routes)

                if not route.get('method', None):
                    route['method'] = []

                self.logger.debug("Configured route '{path}' with methods '{methods}'".format(path=route['path'], methods=route['method']))
                self.route(callback=callback, **route)

        self.wsgi_app = self
        self.wsgi_app.install(ContentTypePlugin())
    def _test_request(self, swagger_plugin=None, method='GET', url='/thing', route_url=None, request_json=VALID_JSON,
                      response_json=VALID_JSON, headers=None, content_type='application/json'):
        if swagger_plugin is None:
            swagger_plugin = self._make_swagger_plugin()
        if response_json is None:
            response_json = {}
        if route_url is None:
            route_url = url

        bottle_app = Bottle()
        bottle_app.install(swagger_plugin)

        @bottle_app.route(route_url, method)
        def do_thing(*args, **kwargs):
            return response_json() if hasattr(response_json, "__call__") else response_json

        test_app = TestApp(bottle_app)
        if method.upper() == 'GET':
            response = test_app.get(url, expect_errors=True, headers=headers)
        elif method.upper() == 'POST':
            if content_type == 'application/json':
                response = test_app.post_json(url, request_json, expect_errors=True, headers=headers)
            else:
                response = test_app.post(url, request_json, content_type=content_type, expect_errors=True, headers=headers)
        else:

            raise Exception("Invalid method {}".format(method))

        return response
Example #5
0
class srv:
    def __init__(self, host='', porta=8080):
        self._h = host
        self._p = porta
        self._a = Bottle()
        self._rota()
        self.estado = '0'

    def _rota(self):
        self._a.route('/breaker', callback=self.disjuntor)
        self._a.route('/breaker', callback=self.set_disjuntor, method='POST')
        self._a.route('/voltage', callback=self.tensao)
        self._a.route('/current', callback=self.corrente)

    def go(self):
        self._a.run(host=self._h, port=self._p)

    def disjuntor(self, estado=None):
        if estado:
            self.estado = estado
        response.headers['Content-Type']='application/json'
        return json.dumps(self.estado)

    def set_disjuntor(self):
        response.headers['Content-Type']='application/json'
        self.estado = request.forms.get('estado')
        return json.dumps(self.estado)

    def tensao(self):
        response.headers['Content-Type']='application/json'
        return json.dumps({'voltage':float('%d.%d' %(random.randint(218,222),random.randint(0,99))),'unit':'V'})

    def corrente(self):
        response.headers['Content-Type']='application/json'
        return json.dumps({'current':float('%d.%d' %(random.randint(1,20),random.randint(0,99))),'unit':'A'})
Example #6
0
def run_rest_server(manager, debug, num_processes, num_threads):
    """Runs the REST server."""
    host = manager.config['server']['rest_host']
    port = manager.config['server']['rest_port']

    install(SaveEnvironmentPlugin(manager))
    install(CheckJsonPlugin())
    install(LoggingPlugin())
    install(oauth2_provider.check_oauth())
    install(CookieAuthenticationPlugin())
    install(UserVerifiedPlugin())
    install(ErrorAdapter())

    for code in xrange(100, 600):
        default_app().error(code)(error_handler)

    root_app = Bottle()
    root_app.mount('/rest', default_app())

    bottle.TEMPLATE_PATH = [os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'views')]

    # We use gunicorn to create a server with multiple processes, since in
    # Python a single process uses at most 1 CPU due to the Global Interpreter
    # Lock.
    sys.argv = sys.argv[:1] # Small hack to work around a Gunicorn arg parsing
                            # bug. None of the arguments to cl should go to
                            # Gunicorn.
    run(app=root_app, host=host, port=port, debug=debug, server='gunicorn',
        workers=num_processes, worker_class='gthread', threads=num_threads,
        timeout=5 * 60)
Example #7
0
def appfactory():
	app = Bottle()
	app.debug = True

	@app.route('/c/<channel>')
	@app.route('/')
	def cb(channel=None):
		return static_file('index.htm', root='./www')

	@app.get('/socket.io/socket.io.js')
	def cb():
		return static_file('socket.io/socket.io.js', root='./www')

	@app.route('/a/recentchannels')
	def cb():
		return {
			'channels':	list(SocketManager.datastore.recall_channel(8))
		}

	@app.get('/socket.io')
	@app.get('/socket.io/')
	@app.get('/socket.io/<path:path>')
	def cb(path=None):
		socketio_manage(bottle.request.environ, {'/channel': SocketManager}, bottle.request)

	@app.route('/<path:path>')
	def cb(path):
		return static_file(path, root='./www')

	return app
Example #8
0
    def test_error_response_case(self):
        def _error_response_func1():
            raise WebApiError('fail567', status=500, result=None)

        decorated1 = json_endpoint(_error_response_func1)

        app1 = Bottle()
        app1.route('/', ['GET'], decorated1)

        wt1 = TestApp(app1)
        resp1 = wt1.get('/', status=500)

        eq_(resp1.status_int, 500)
        eq_(resp1.content_type, 'application/json')
        eq_(resp1.body, '{"status": "error", "message": "fail567", "result": null}')
        eq_(resp1.headers['Pragma'], 'no-cache')
        eq_(resp1.headers['Cache-Control'], 'no-cache')

        # test JSONP
        resp2 = wt1.get('/', params=dict(j='j345'), status=500)
        eq_(resp2.status_int, 500)
        eq_(resp2.content_type, 'application/javascript')
        eq_(resp2.body, 'j345({"status": "error", "message": "fail567", "result": null});')
        eq_(resp2.headers['Pragma'], 'no-cache')
        eq_(resp2.headers['Cache-Control'], 'no-cache')
Example #9
0
    def test_success_response_case(self):
        def _success_response_func1():
            return dict(value=123)

        decorated1 = json_endpoint(_success_response_func1)

        app1 = Bottle()
        app1.route('/', ['GET'], decorated1)

        wt1 = TestApp(app1)
        resp1 = wt1.get('/', status=200)

        eq_(resp1.status_int, 200)
        eq_(resp1.content_type, 'application/json')
        eq_(resp1.body, '{"status": "ok", "result": {"value": 123}}')
        eq_(resp1.headers['Pragma'], 'no-cache')
        eq_(resp1.headers['Cache-Control'], 'no-cache')

        # test JSONP
        resp2 = wt1.get('/', params=dict(j='j345'), status=200)
        eq_(resp2.status_int, 200)
        eq_(resp2.content_type, 'application/javascript')
        eq_(resp2.body, 'j345({"status": "ok", "result": {"value": 123}});')
        eq_(resp2.headers['Pragma'], 'no-cache')
        eq_(resp2.headers['Cache-Control'], 'no-cache')
def test_bottle_peewee():

    app = Bottle()
    db = PeeweePlugin('sqlite:///:memory:')

    class Role(Model):
        name = CharField()

        class Meta(object):
            database = db.proxy

    class User(Model):
        name = CharField()
        created = DateTimeField(default=dt.datetime.now)

        role = ForeignKeyField(Role)

        class Meta(object):
            database = db.proxy

    app.install(db)

    db.database.create_tables([User, Role])
    User.create(name='test', role=Role.create(name='admin'))
    assert [user for user in User.select()]

    data = db.to_dict(User.get())
    assert data
    assert data['name'] == 'test'
    assert data['created']
Example #11
0
def test_bottle_jade():
    from bottle import Bottle
    from bottle_jade import JadePlugin
    from os import path as op
    import webtest

    app = Bottle()
    templates = op.dirname(op.abspath(__file__))
    jade = app.install(JadePlugin(template_folder=templates))

    @app.route("/")
    def index():
        context = {"variable": "value"}
        return jade.render("index.jade", **context)

    @app.route("/simple")
    @jade.view("simple.jade")
    def simple():
        context = {}
        return context

    client = webtest.TestApp(app)
    response = client.get("/")
    assert b"Hello world" in response.body
    assert b"localhost" in response.body

    response = client.get("/simple")
    assert b"Simple" in response.body
    def run(self):
        #create the logger
        try:
            self._smgr_log = ServerMgrlogger()
        except:
            print "Error Creating logger object"

        # Connect to the cluster-servers database
        try:
            self._status_serverDb = db(
                self._smgr_main._args.server_manager_base_dir+self._smgr_main._args.database_name)
        except:
            self._smgr_log.log(self._smgr_log.DEBUG,
                     "Error Connecting to Server Database %s"
                    % (self._smgr_main._args.server_manager_base_dir+self._smgr_main._args.database_name))
            exit()

        #set the status related handlers
        status_bottle_app = Bottle()
        status_bottle_app.route('/server_status', 'POST', self.put_server_status)
        status_bottle_app.route('/server_status', 'PUT', self.put_server_status)
        self._base_obj = self._status_thread_config['base_obj']

        try:
            bottle.run(status_bottle_app,
                       host=self._status_thread_config['listen_ip'],
                       port=self._status_thread_config['listen_port'])
        except Exception as e:
            # cleanup gracefully
            exit()
Example #13
0
class WebServerThread(multiprocessing.Process):
    """Thread to handle the webserver"""
    def __init__(self, queue):
        multiprocessing.Process.__init__(self)
        self.app = Bottle()
        self.queue = queue
        self.path = os.path.dirname(os.path.realpath(__file__))

    def run(self):
        """Serve the webapp with bottle, and handle moves sent via JS"""
        @self.app.route('/<filename:path>')
        def send_static(filename):
            return static_file(filename,
                               root=(self.path + "/../../frontend"))

        @self.app.route('/')
        def send_static_index():
            return static_file('index.html',
                               root=(self.path + "/../../frontend"))

        @self.app.route('/communicate')
        def get():
            self.queue.put(request.query.move or "")
            return 'ACK'

        try:
            self.app.run(quiet=True)
        except Exception, ex:
            print ex
Example #14
0
class RecServer:
    def __init__(self):
        self._app = Bottle()
        self._route()

        self.db = RecDB(get_config()['DB_URI'])

    def _route(self):
        ### This is the API part of the app
        # TODO: move to namespace /api/
        # TODO: create a "sub-application"

        ## Static part of the site
        self._app.route('/output/<filepath:path>',
                        callback=lambda filepath:
                        static_file(filepath,
                                    root=get_config()['AUDIO_OUTPUT']))
        self._app.route('/static/<filepath:path>',
                        callback=lambda filepath: static_file(filepath,
                                                              root='static/'))
        self._app.route('/', callback=lambda: redirect('/new.html'))
        self._app.route('/new.html',
                        callback=partial(static_file, 'new.html',
                                         root='pages/'))
        self._app.route('/tempo.html',
                        callback=partial(static_file, 'tempo.html',
                                         root='pages/'))
Example #15
0
 def __init__(self, credentials_manager, updown_auth_manager,
              ssl_enabled, server_version, min_client_compatible_version,
              *argc, **argv):
     self.credentials_manager = credentials_manager
     self.updown_auth_manager = updown_auth_manager
     self.ssl_enabled = ssl_enabled
     self.server_version = server_version
     self.min_client_compatible_version = min_client_compatible_version
     Bottle.__init__(self, *argc, **argv)
    def __init__(self, application):
        Bottle.__init__(self)
        self._application = application
        self._path = '/shoutbox'
        self._chat = [(datetime.now(), "PirateBox", "Chat and share files anonymously!", "def")]
        self._etag = hashlib.sha1(str(self._chat)).hexdigest()

        self.get('/content')(self._getContent)
        self.post('/line')(self._addLine)
Example #17
0
    def wsgi(self):
        if not self._handlers:
            raise
        from bottle import Bottle
        from werobot.contrib.bottle import make_view

        app = Bottle()
        app.route('<t:path>', ['GET', 'POST'], make_view(self))
        return app
Example #18
0
def run_rest_server(manager, debug, num_processes, num_threads):
    """Runs the REST server."""
    host = manager.config['server']['rest_host']
    port = manager.config['server']['rest_port']

    install(SaveEnvironmentPlugin(manager))
    install(CheckJsonPlugin())
    install(LoggingPlugin())
    install(oauth2_provider.check_oauth())
    install(CookieAuthenticationPlugin())
    install(UserVerifiedPlugin())
    install(PublicUserPlugin())
    install(ErrorAdapter())

    # Replace default JSON plugin with one that handles datetime objects
    # Note: ErrorAdapter must come before JSONPlugin to catch serialization errors
    uninstall(JSONPlugin())
    install(JSONPlugin(json_dumps=DatetimeEncoder().encode))

    # JsonApiPlugin must come after JSONPlugin, to inspect and modify response
    # dicts before they are serialized into JSON
    install(JsonApiPlugin())

    for code in xrange(100, 600):
        default_app().error(code)(error_handler)

    root_app = Bottle()
    root_app.mount('/rest', default_app())

    # Look for templates in codalab-worksheets/views
    bottle.TEMPLATE_PATH = [
        os.path.join(
            os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'views'
        )
    ]

    # Increase the request body size limit to 8 MiB
    bottle.BaseRequest.MEMFILE_MAX = 8 * 1024 * 1024

    # We use gunicorn to create a server with multiple processes, since in
    # Python a single process uses at most 1 CPU due to the Global Interpreter
    # Lock.
    sys.argv = sys.argv[:1]  # Small hack to work around a Gunicorn arg parsing
    # bug. None of the arguments to cl should go to
    # Gunicorn.
    run(
        app=root_app,
        host=host,
        port=port,
        debug=debug,
        server='gunicorn',
        workers=num_processes,
        worker_class='gthread',
        threads=num_threads,
        worker_tmp_dir='/tmp',  # don't use globally set tempdir
        timeout=5 * 60,
    )
Example #19
0
class CQHttp(_ApiClient):
    def __init__(self, api_root=None, token=None):
        super().__init__(api_root, token)
        self.handlers = {
            'message': {},
            'event': {},
            'request': {}
        }
        self.app = Bottle()
        self.app.post('/')(self.handle)

    on_message = _deco_maker('message')
    on_event = _deco_maker('event')
    on_request = _deco_maker('request')

    def handle(self):
        if self.auth and request.headers.get('Authorization') != self.auth:
            abort(401)

        post_type = request.json.get('post_type')
        if post_type not in ('message', 'event', 'request'):
            abort(400)

        handler_key = None
        for pk_pair in (
                ('message', 'message_type'),
                ('event', 'event'),
                ('request', 'request_type'),
        ):
            if post_type == pk_pair[0]:
                handler_key = request.json.get(pk_pair[1])
                if not handler_key:
                    abort(400)
                else:
                    break

        if not handler_key:
            abort(400)

        handler = self.handlers[post_type].get(handler_key)
        if not handler:
            handler = self.handlers[post_type].get('*')  # try wildcard handler
        if handler:
            assert callable(handler)
            return handler(request.json)
        return ''

    def run(self, host=None, port=None, **kwargs):
        self.app.run(host=host, port=port, **kwargs)

    def send(self, context, message, **kwargs):
        if context.get('group_id'):
            return self.send_group_msg(group_id=context['group_id'], message=message, **kwargs)
        elif context.get('discuss_id'):
            return self.send_discuss_msg(discuss_id=context['discuss_id'], message=message, **kwargs)
        elif context.get('user_id'):
            return self.send_private_msg(user_id=context['user_id'], message=message, **kwargs)
Example #20
0
 def test_setattr(self):
     """ Attributed can be assigned, but only once. """
     app = Bottle()
     app.test = 5
     self.assertEqual(5, app.test)
     self.assertRaises(AttributeError, setattr, app, 'test', 6) 
     del app.test
     app.test = 6
     self.assertEqual(6, app.test)
Example #21
0
class AdminSite(object):
    """
    Creates an admin site for models
    """

    url_prefix = '/admin'

    def __init__(self, app=None):
        self.app = Bottle()
        self._registry = []

    def register(self, model=None):
        if model in self._registry:
            raise AlreadyRegistered(u'Model {} has already beeen registered'.format(model))
        self._registry.append(model)

    def setup_routing(self, app):
        self.app.route(
            '/',
            ['GET'],
            home_view)

        self.app.route(
            '/<model_name>/add'.format(prefix=self.url_prefix),
            ['GET'],
            add_model_view)

        app.mount(self.url_prefix, self.app)

    def _build_models_dict(self):
        """
        Build the models dict containing the URLs for each action and model
        """

        models_dict = {}
        for model in self._registry:
            model_data = {}

            model_name = model.__name__.lower()
            model_data['name'] = model_name

            mapper = inspect(model)
            attrs = [prop.columns[0] for prop in mapper.attrs]
            model_data['columns'] = [{'name': prop.name} for prop in attrs
                                     if prop.name != 'id']

            model_data['add_url'] = '{}/{}/add'.format(self.url_prefix, model_name)
            model_data['list_url'] = '{}/{}'.format(self.url_prefix, model_name)
            model_data['change_url'] = '{}/{}/change'.format(self.url_prefix, model_name)
            model_data['delete'] = '{}/{}/delete'.format(self.url_prefix, model_name)

            models_dict[model] = model_data
        return models_dict

    def get_model_list(self):
        models_dict = self._build_models_dict()
        return sorted(models_dict.values(), key=lambda x: x['name'].lower())
    def __init__(self, application, path):
        Bottle.__init__(self)
        self._application = application
        self._path = path
        self._mimeTypes = MimeTypes(['plugins/shared/mime.types'], strict=False)

        self.get('/files/')(self.shared)
        self.get('/files/<filepath:path>')(self.shared)
        self.get('/')(self.files)
        self.get('/<filepath:path>')(self.files)
Example #23
0
class server(object):

    def __init__(self, json):
        self._app = Bottle()
        self.config = configuration_loader(json)
        routes = route_loader(self._app, self.config.mongo_datas)
        routes.load_all_route()

    def start(self):
        self._app.run(host="172.20.10.14", port=8080)
Example #24
0
    def __init__(self, credentials_manager, updown_auth_manager,
                 server_version, min_client_compatible_version,
                 server_capabilities, *argc, **argv):

        self.credentials_manager = credentials_manager
        self.updown_auth_manager = updown_auth_manager
        self.server_version = server_version
        self.min_client_compatible_version = min_client_compatible_version
        self.server_capabilities = server_capabilities
        Bottle.__init__(self, *argc, **argv)
    def run(self):
        app = Bottle()

        @app.route("/")
        @app.route("/<url:re:.+>")
        def catch_all_requests(url=None):
            return 'You requested %s\n' % request.path

        self._server = MyWSGIRefServer(host=Server.HOSTNAME, port=Server.PORT)
        app.run(server=self._server)
Example #26
0
    def __init__(self, doc_root_snap=".", snap_extensions={}, doc_root_overlay=None):

        Bottle.__init__(self)

        self.doc_root_snap = doc_root_snap
        self.snap_extensions = snap_extensions
        self.doc_root_overlay = doc_root_overlay

        self.route("/snap/libraries/<file_path>", callback=self.serve_library)
        self.route("/snap/<file_path:path>", callback=self.serve_snap)
Example #27
0
def start():
    app = Bottle()
    app.mount('/1', v1.app)
    app.mount('/2', v2.app)
    app.mount('/3', v3.app)
    app.mount('/stats', stats.app)
    app.mount('/sync', sync.app)

    @app.get('/')
    def home(): redirect('/3')

    @app.get('/api')
    @app.get('/api/')
    @app.get('/api/<path:re:(.*)>')
    def api1(path=''): redirect('/1/%s?%s' % (path, request.query_string))

    @app.get('/api2')
    @app.get('/api2/')
    @app.get('/api2/<path:re:(.*)>')
    def api2(path=''): redirect('/2/%s?%s' % (path, request.query_string))

    debug(common.config.getboolean('Settings', 'debug'))
    run(app=app,
        port=common.config.getint('Settings', 'port'),
        host=common.config.get('Settings', 'address'),
        server=common.config.get('Settings', 'app_server'),
        reloader=common.config.getboolean('Settings', 'debug')
    )
Example #28
0
 def __init__(self, sdc, cfg):
     self.sdc = sdc
     self.weather_server_ip = cfg.get("weather", "server")
     self.weather_server_port = cfg.get("weather", "port")
     self.weather_api_key = cfg.get("weather", "apikey")
     self.zipcode = cfg.get("weather", "zipcode")
     Bottle.__init__(self)
     self.route("/", callback=self.index)
     self.route("/alarms", callback=self.alarms)
     self.route("/reset", callback=self.reset_alarms)
     self.route("/weather", callback=self.weather)
Example #29
0
 def test_static(self):
     """ Routes: Static routes """
     app = Bottle()
     token = 'abc'
     routes = ['','/','/abc','abc','/abc/','/abc/def','/abc/def.ghi']
     for r in routes:
         app.add_route(r, token, simple=True)
     self.assertTrue('GET' in app.simple_routes)
     r = [r for r in app.simple_routes['GET'].values() if r == 'abc']
     self.assertEqual(5, len(r))
     for r in routes:
         self.assertEqual(token, app.match_url(r)[0])
Example #30
0
 def test_mount_no_plugins(self):
     def plugin(func):
         def wrapper(*a, **ka):
             return 'Plugin'
         return wrapper
     self.app.install(plugin)
     app = Bottle()
     self.app.mount(app, '/prefix')
     app.route('/foo', callback=lambda: 'bar')
     self.app.route('/foo', callback=lambda: 'baz')
     self.assertBody('Plugin', '/foo')
     self.assertBody('bar', '/prefix/foo')
Example #31
0
import os
import urllib

from google.appengine.api import users
from google.appengine.ext import ndb

import jinja2
from bottle import Bottle, request, redirect, debug

debug(True)

bottle = Bottle()

JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(
    os.path.dirname(__file__)),
                                       extensions=['jinja2.ext.autoescape'],
                                       autoescape=True)

DEFAULT_GUESTBOOK_NAME = 'guestbook'

# We set a parent key on the 'Greetings' to ensure that they are all in the same
# entity group. Queries across the single entity group will be consistent.
# However, the write rate should be limited to ~1/second.


def guestbook_key(guestbook_name=DEFAULT_GUESTBOOK_NAME):
    """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
    return ndb.Key('Guestbook', guestbook_name)


class Greeting(ndb.Model):
Example #32
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

### Microserviço para expor a inserção de transação
from json import dumps
from bottle import Bottle, request, response
from app.core import (search_all_users,
                     insert_user,
                     insert_transfer,
                     search_transfer_by_date,
                     search_transfer_by_pagador,
                     search_transfer_by_beneficiario)

app = Bottle()

@app.get('/')
def index_map(): #chamada teste do bdd convocando a raiz
    return dumps({"usuarios": "url/usuarios","transferencia":"url/transferencia"})

@app.get('/transferencia/<date>')
def transfer_map(date): #
    return search_transfer_by_date(date)

@app.get('/transferencia/pagador/<nome>')
def transfer_map(nome): #
    return search_transfer_by_pagador(nome)

@app.get('/transferencia/beneficiario/<nome>')
def transfer_map(nome): #
    return search_transfer_by_beneficiario(nome)
Example #33
0
 def get_bottle_app(self):
     """Returns bottle instance"""
     self.app = Bottle()
     self.dispatch_views()
     return self.app    
Example #34
0
#! /usr/bin/env python
import json
from bottle import Bottle, route, run, static_file, jinja2_template as template, jinja2_view as view
from datetime import date

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

app = Bottle()
dict_cal = {'today': date.today().strftime("%Y-%m-%d")}


@app.route('/static/<filepath:path>')
def server_static(filepath):
    return static_file(filepath, root='./static/')


@app.route('/')
@app.route('/notifications', name='notifications')
def notifications():
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.login("*****@*****.**", "GibberishGoliath007")
    msg = "\nHello!"  # The /n separates the message from the headers
    server.sendmail("*****@*****.**", "*****@*****.**", msg)
    return template('landing.tpl', cal=dict_cal)


app.run(host='0.0.0.0', port=5004, reloader=True, debug=True)

##
Example #35
0
@author: alex
"""

from pygtail.core import Pygtail
from datetime import datetime
import socket
from lxml import etree
import lxml.builder as lb
from bottle import Bottle, run

mes = [
    "Unk", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec"
]

server = Bottle()


@server.route('/ssh')
def read_log():
    da = datetime.now()
    data = da.strftime('%Y-%m-%dT%H:%M:%f')
    filename = '/home/alex/Documentos/ssh.log'
    nome = socket.getfqdn()
    ip = socket.gethostbyname(socket.gethostname())
    mensagem = etree.Element('message')
    hostXML = etree.Element('host', name=nome, ip=ip)
    mensagem.append(hostXML)
    reportXML = etree.Element('report', date=data)
    mensagem.append(reportXML)
    payload = etree.Element('payload')
Example #36
0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
''' OCW UI Backend web services initialization. '''

from bottle import Bottle, response, static_file
from local_file_metadata_extractors import lfme_app
from directory_helpers import dir_app
from rcmed_helpers import rcmed_app
from processing import processing_app

app = Bottle()
app.mount('/lfme/', lfme_app)
app.mount('/dir/', dir_app)
app.mount('/rcmed/', rcmed_app)
app.mount('/processing/', processing_app)

@app.route('/')
@app.route('/index.html')
def index():
    return static_file('index.html', root='./frontend/app/')

@app.route('/bower_components/:path#.+#')
def serve_static(path):
    return static_file(path, root='./frontend/bower_components/')

@app.route('/styles/:path#.+#')
Example #37
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from bottle import Bottle, request
from sqlalchemy.sql import select
from config.models import Sensor
from config.database import engine, session_db

sensor_view = Bottle()


@sensor_view.route('/listar', method='GET')
def listar():
    conn = engine.connect()
    stmt = select([Sensor])
    return json.dumps([dict(r) for r in conn.execute(stmt)])


@sensor_view.route('/listar/<estacion_id>', method='GET')
def listar_estacion(estacion_id):
    conn = engine.connect()
    stmt = """
		SELECT S.id, S.nombre, S.descripcion, (U.nombre || ',' || U.simbolo) AS unidad_medida, S.unidad_medida_id 
		FROM sensores S INNER JOIN unidad_medidas U ON U.id = S.unidad_medida_id
		WHERE S.estacion_id = :estacion_id
		"""
    return json.dumps(
        [dict(r) for r in conn.execute(stmt, {'estacion_id': estacion_id})])


@sensor_view.route('/guardar', method='POST')
Example #38
0
    def __init__(self, credentials_manager, server_capabilities):

        self.credentials_manager = credentials_manager
        self.server_capabilities = server_capabilities
        Bottle.__init__(self)
                    pass

            self.options['handler_class'] = QuietHandler
        self.server = make_server(self.host, self.port, handler,
                                  **self.options)
        self.server.serve_forever()

    def stop(self):
        # self.server.server_close() <--- alternative but causes bad fd exception
        self.server.shutdown()


listen_addr = '127.0.0.1'

listen_port = 10001
app = Bottle()
server = MyWSGIRefServer(host=listen_addr, port=listen_port)
#####################################################################
#                       START APP HERE                              #
#####################################################################
tf_log = 'tf.log'


#http://127.0.0.1:10001/calculate?number1=7659&number2=7762&operation=addition
@app.route('/calculate')
def index():
    #    http://blog.tplus1.com/blog/2007/09/28/the-python-logging-module-is-much-better-than-print-statements/
    logfun = logging.getLogger("logfun")

    #https://stackoverflow.com/questions/31405812/how-to-get-client-ip-address-using-python-bottle-framework
    client_ip = request.environ.get('REMOTE_ADDR')
Example #40
0
"""

from collections import namedtuple
from functools import wraps
import json
import os
import tempfile

from bottle import abort, request, response, Bottle
from future.utils import viewitems

from ivre import config, utils, VERSION
from ivre.db import db
from ivre.web import utils as webutils

application = Bottle()

#
# Utils
#


def check_referer(func):
    """"Wrapper for route functions to implement a basic anti-CSRF check
based on the Referer: header.

    It will abort if the referer is invalid.

    """

    if config.WEB_ALLOWED_REFERERS is False:
Example #41
0
"""
HSBXL inventory web app.
"""

import os.path
import json

from bottle import Bottle, template, static_file, request, response
import rethinkdb as r

HERE = os.path.dirname(os.path.realpath(__file__))

bottle = Bottle()
r.connect("localhost", 28015).repl()

if "inventory" not in r.db_list().run():
    r.db_create("inventory").run()
    r.db("inventory").table_create("items").run()

items = r.db("inventory").table("items")


@bottle.route('/')
def index():
    return static_file('index.html', root=os.path.join(HERE, 'static'))


@bottle.route('/item/')
def index():
    all_items = items.filter(dict(request.query)).run()
    return template(os.path.join(HERE, 'views/items'), items=all_items)
Example #42
0
from bottle import Bottle, run, route, static_file, request, response, template, redirect
from string import Template
import json

import ipfsapi

api = ipfsapi.connect('https://ipfs.infura.io', 5001)

app = Bottle(__name__)


@app.get('/')
def root():
    return 'Root'


@app.get('/send/<data_str>')
def sendIPFS(data_str):

    res = api.add_json({'data': data_str})

    return {'status': 'ok', 'ipfs_hash': res}


@app.get('/get/<ipfs_hash>')
def getIPFS(ipfs_hash):

    res = api.cat(ipfs_hash)

    return {'status': 'ok', 'data': res}
Example #43
0
from bottle import Bottle, request, route, run, template, get
import kafka_selfservice

app = Bottle()


@app.get('/v1/ping')
def ping():
    return ('pong')


app.run(host='localhost', port=8080, debug=True)
Example #44
0
class CSG2Server:
    runningsessions = {}

    def __init__(self, themedir, siteconftemplate):
        self.installdir = sys.path[
            0]  # Note: this should ideally be gotten from somewhere else.
        self.wsgiapp = Bottle()
        self.apiclass = sandbox.csg2api(self.wsgiapp, self.runningsessions)

        # Parse arguments
        argparser = argparse.ArgumentParser()
        argparser.add_argument('sitesfolder',
                               metavar='<site storage folder>',
                               help="path to the folder containing sites")
        argparser.add_argument('siteroot',
                               metavar='<site name>',
                               help="site name/the folder with config.json")
        self.parsedargs = argparser.parse_args()

        # Setup configuration and path to site
        self.sitepath = os.path.abspath(
            os.path.join(self.parsedargs.sitesfolder,
                         self.parsedargs.siteroot))
        siteconffile = open(os.path.join(self.sitepath, "config.json"),
                            mode="rt",
                            encoding="utf-8")
        self.siteconf = configman.normalize_config(json.load(siteconffile),
                                                   self.parsedargs.siteroot)
        siteconffile.close()

        # Setup theming
        themesroot = os.path.abspath(themedir)
        self.themepath = os.path.join(themesroot,
                                      self.siteconf["site"]["theme"])
        os.chdir(self.sitepath)

        # Assign routes (done before the site code to allow overrides)
        # This is functionally equivalent of what the language does, but makes sure Bottle will call the right instance.
        self.getrandstaticredirect = self.wsgiapp.route(
            "/rand/<filepath:path>")(self.getrandstaticredirect)
        self.getstatic = self.wsgiapp.route("/static/<filepath:path>")(
            self.getstatic)
        self.compilethemesass = self.wsgiapp.route("/theme/sass/master.scss")(
            self.compilethemesass)
        self.getthemeasset = self.wsgiapp.route(
            "/theme/static/<filepath:path>")(self.getthemeasset)
        self.compilesass = self.wsgiapp.route("/sass/<filename:re:.*\.scss>")(
            self.compilesass)
        self.catchall = self.wsgiapp.route("/")(
            self.wsgiapp.route("/<filepath:path>")(view(
                os.path.join(self.themepath, "master.tpl"))(self.catchall)))
        self.dologin = self.wsgiapp.route("/login",
                                          method="POST")(self.dologin)

        # If they have code, run it
        if "additional_code" in self.siteconf["site"]:
            oldpath = sys.path
            sys.path[0] = self.sitepath
            importlib.invalidate_caches()
            with open(os.path.join(self.sitepath,
                                   self.siteconf["site"]["additional_code"]),
                      mode="rt") as codefile:
                sandbox.create_box(
                    codefile.read(), self.wsgiapp, apiclass=self.apiclass
                )  # This file is excempt from the linking clauses in the license, allowing it to be non-(A)GPL.
            sys.path = oldpath
            importlib.invalidate_caches()

        # Configure Nginx
        socketpath = "/tmp/csg2_{}.sock".format(
            self.siteconf["site"]["domain_name"].replace(".", "_"))
        print("-> Generating config.")
        with open(os.path.abspath(siteconftemplate),
                  mode="rt",
                  encoding="utf-8") as sitetemplate:
            sitetemplatetxt = sitetemplate.read()
            newsite = sitetemplatetxt.replace(
                "%%SERVERNAME%%",
                self.siteconf["site"]["domain_name"]).replace(
                    "%%SOCKETPATH%%", socketpath)
            with open("/tmp/{}.csg2nginx".format(
                    self.siteconf["site"]["domain_name"].replace(".", "_")),
                      mode="wt",
                      encoding="utf-8") as newconf:
                newconf.write(newsite)

        # Serve site.
        print("-> Serving up site on '{}'.".format(socketpath))
        waitress_serve(self.wsgiapp, unix_socket=socketpath)

    # Route: "/rand/<filepath:path>"
    def getrandstaticredirect(self, filepath):
        extmap = {
            "image": [
                "png", "jpg", "jpeg", "gif"
            ]  # Using "image" as extention allows matching with all image types
        }
        response.status = 307  # Temporary Redirect
        modfilepath = filepath.split(".")
        targetmap = modfilepath[-1:]
        matches = []
        if modfilepath[-1] in extmap.keys():
            targetmap = extmap[modfilepath[-1]]
        for ext in targetmap:
            modfilepathstr = ".".join(modfilepath[:-1] + ["*"] + [ext])
            matches = matches + glob.glob(
                os.path.join(self.sitepath, "static/", modfilepathstr))
        if len(matches) == 0:
            response.status = 404
            return "Files not found."
        pick = random.choice(matches).replace(self.sitepath,
                                              "").replace("\\", "/")
        response.set_header("Location", pick)
        return ""

    # Route: "/static/<filepath:path>"
    def getstatic(self, filepath):
        response.set_header("Cache-Control", "max-age=300")
        return static_file(filepath,
                           root=os.path.join(self.sitepath, "static/"))

    # Route: "/theme/sass/master.scss"
    def compilethemesass(self):
        output = ""
        response.set_header("Cache-Control", "max-age=300")
        response.content_type = "text/css"
        with open(os.path.join(self.sitepath, "scss/theme.scss"),
                  mode="rt") as fl:
            output += fl.read()
        with open(os.path.join(self.themepath, "master.scss"),
                  mode="rt") as fl:
            output += fl.read()
        return sass.compile(string=output)

    # Route: "/theme/static/<filepath:path>"
    def getthemeasset(self, filepath):
        response.set_header("Cache-Control", "max-age=300")
        return static_file(filepath,
                           root=os.path.join(self.themepath, "assets/"))

    # Route: "/sass/<filename:re:.*\.scss>"
    def compilesass(self, filename):
        output = ""
        response.set_header("Cache-Control", "max-age=300")
        response.content_type = "text/css"
        if not os.path.exists(os.path.join(self.sitepath, "scss/" + filename)):
            response.status = 404
            return "SCSS file not found."
        with open(os.path.join(self.sitepath, "scss/" + filename),
                  mode="rt") as fl:
            output += fl.read()
        return sass.compile(string=output)

    # Route: "/"
    # Route: "/<filepath:path>"
    def catchall(self, filepath="index"):
        if filepath[-1] == "/":
            filepath = filepath[:-1]
        pageindex = -1
        for i in range(0, len(self.siteconf["pages"])):
            if self.siteconf["pages"][i]["path"] == filepath:
                pageindex = i
                break
        templatepath = os.path.join(self.sitepath, filepath + ".tpl")
        if not os.path.exists(templatepath):
            templatepath = os.path.join(self.installdir, "default-files/",
                                        filepath + ".tpl")
            if not os.path.exists(templatepath):
                response.status = 404
                return "Page not found :C"

        if self.apiclass.authhook != None:
            response.set_header("Cache-Control", "no-cache")
            if (self.siteconf["pages"][pageindex]["require_auth"]) and (
                    request.get_cookie("csg2sess")
                    not in self.runningsessions) and (filepath != "login"):
                response.status = "307 Not Logged In"
                response.set_header("Location", "/login")
                return ""
        else:
            response.set_header("Cache-Control", "max-age=300")

        return {
            "title":
            self.siteconf["site"]["title"],
            "link_elements":
            self.siteconf["pages"][pageindex]["link_elements"],
            "nav_links": [(
                "/" + k["path"],
                k["title"],
            ) for k in self.siteconf["pages"] if k["hidden"] == False],
            "content":
            templatepath,
            "csg2api":
            self.apiclass
        }

    #Route: "/login", method="POST"
    def dologin(self):
        if self.apiclass.authhook == None:
            response.status = "303 No Need To Log In"
            response.set_header("Location", "/")
            return ""
        if self.apiclass.authhook(request.forms.user, request.forms.password):
            uid = uuid.uuid4().hex + uuid.uuid4().hex
            response.set_cookie("csg2sess", uid)
            self.runningsessions[uid] = request.forms.user
            response.status = "303 Successfully Logged In"
            response.set_header("Location", "/")
            return ""
        else:
            response.status = "303 Incorrect Credentials"
            response.set_header("Location", "/login")
            return ""
Example #45
0
        if tag == 'START':
            pass
        else:
            model[word] = tag
    except ValueError:
        pass
read_file.close()


def get_word_features(text):
    test_words = text.split()
    testMatrix = word_model.transform(test_words)
    return testMatrix


app = Bottle()


@app.route('/')
def index():
    """Home Page"""

    return template("form.tpl", info="", stm="")


@app.route('/api/formhandler', method='POST')
def formhandler():
    temp_response = []
    sentence = request.forms.get('first')

    feature_matrix = get_word_features(sentence)
Example #46
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from bottle import Bottle
from bottle.ext.mongo import MongoPlugin
import datetime

from redis import Redis
from rq import Queue

from mining.utils import conf, parse_dumps
from .base import get, post, put, delete

collection = 'cube'

cube_app = Bottle()
mongo = MongoPlugin(uri=conf("mongodb")["uri"],
                    db=conf("mongodb")["db"],
                    json_mongo=True)
cube_app.install(mongo)


@cube_app.route('/', method='GET')
@cube_app.route('/<slug>', method='GET')
def cube_get(mongodb, slug=None):
    return get(mongodb, collection, slug)


@cube_app.route('/runing-cubes', method='GET')
def cube_get_runing(mongodb, slug=None):
    cubes = list(mongodb[collection].find({
Example #47
0
class terrariumWebserver():

    app = Bottle()
    app.install(terrariumWebserverHeaders())

    def __init__(self, terrariumEngine):
        self.__terrariumEngine = terrariumEngine
        self.__app = terrariumWebserver.app
        self.__config = self.__terrariumEngine.get_config('system')
        self.__caching_days = 30

        terrariumWebserver.app.terrarium = self.__terrariumEngine
        # Load language
        gettext.translation('terrariumpi',
                            'locales/',
                            languages=[
                                self.__terrariumEngine.config.get_language()
                            ]).install(True)
        self.__translations = terrariumTranslations()

        self.__routes()

    def __authenticate(self, user, password):
        return self.__terrariumEngine.authenticate(user, password)

    def __logout_authenticate(self, user, password):
        return True

    def __routes(self):
        self.__app.route('/', method="GET", callback=self.__render_page)
        self.__app.route('/<template_name:re:[^/]+\.html$>',
                         method="GET",
                         callback=self.__render_page)

        self.__app.route('/<filename:re:robots\.txt>',
                         method="GET",
                         callback=self.__static_file)
        self.__app.route(
            '/<root:re:(static|gentelella|webcam|audio)>/<filename:path>',
            method="GET",
            callback=self.__static_file)

        self.__app.route('/api/<path:path>',
                         method=['GET'],
                         callback=self.__get_api_call)

        self.__app.route('/api/switch/toggle/<switchid:path>',
                         method=['POST'],
                         callback=self.__toggle_switch,
                         apply=auth_basic(
                             self.__authenticate,
                             _('TerrariumPI') + ' ' + _('Authentication'),
                             _('Authenticate to make any changes')))

        self.__app.route('/api/switch/state/<switchid:path>/<value:int>',
                         method=['POST'],
                         callback=self.__state_switch,
                         apply=auth_basic(
                             self.__authenticate,
                             _('TerrariumPI') + ' ' + _('Authentication'),
                             _('Authenticate to make any changes')))

        self.__app.route(
            '/api/config/<path:re:(system|weather|switches|sensors|webcams|doors|audio|environment|profile)>',
            method=['PUT', 'POST', 'DELETE'],
            callback=self.__update_api_call,
            apply=auth_basic(self.__authenticate,
                             _('TerrariumPI') + ' ' + _('Authentication'),
                             _('Authenticate to make any changes')))

        self.__app.route(
            '/api/audio/player/<action:re:(start|stop|volumeup|volumedown|mute|unmute)>',
            method=['POST'],
            callback=self.__player_commands,
            apply=auth_basic(self.__authenticate,
                             _('TerrariumPI') + ' ' + _('Authentication'),
                             _('Authenticate to make any changes')))

        self.__app.route('/api/audio/file',
                         method=['POST'],
                         callback=self.__upload_audio_file,
                         apply=auth_basic(
                             self.__authenticate,
                             _('TerrariumPI') + ' ' + _('Authentication'),
                             _('Authenticate to make any changes')))

        self.__app.route('/api/audio/file/<audiofileid:path>',
                         method=['DELETE'],
                         callback=self.__delete_audio_file,
                         apply=auth_basic(
                             self.__authenticate,
                             _('TerrariumPI') + ' ' + _('Authentication'),
                             _('Authenticate to make any changes')))

        self.__app.route('/logout',
                         method=['GET'],
                         callback=self.__logout_url,
                         apply=auth_basic(
                             self.__logout_authenticate,
                             _('TerrariumPI') + ' ' + _('Authentication'),
                             _('Authenticate to make any changes')))

    def __template_variables(self, template):
        variables = {
            'lang':
            self.__terrariumEngine.config.get_language(),
            'title':
            self.__config['title'],
            'version':
            self.__config['version'],
            'page_title':
            _(template.replace('_', ' ').capitalize()),
            'temperature_indicator':
            self.__terrariumEngine.get_temperature_indicator(),
            'translations':
            self.__translations
        }

        if 'index' == template or 'profile' == template:
            variables['person_name'] = self.__terrariumEngine.get_profile_name(
            )
            variables[
                'person_image'] = self.__terrariumEngine.get_profile_image()

        elif 'webcam' == template or 'webcam_settings' == template:
            variables[
                'amount_of_webcams'] = self.__terrariumEngine.get_amount_of_webcams(
                )

        elif 'door_status' == template:
            variables[
                'amount_of_doors'] = self.__terrariumEngine.get_amount_of_doors(
                )

        elif 'switch_status' == template:
            variables[
                'amount_of_switches'] = self.__terrariumEngine.get_amount_of_switches(
                )

        elif 'sensor_temperature' == template:
            variables[
                'amount_of_sensors'] = self.__terrariumEngine.get_amount_of_sensors(
                    'temperature')

        elif 'sensor_humidity' == template:
            variables[
                'amount_of_sensors'] = self.__terrariumEngine.get_amount_of_sensors(
                    'humidity')

        return variables

    def __render_page(self, template_name='index.html'):
        template_name = template_name[:-5]

        if not os.path.isfile('views/' + template_name + '.tpl'):
            template_name = '404'

        return template(template_name,
                        **self.__template_variables(template_name))

    def __static_file(self, filename, root='static'):
        if filename == 'js/terrariumpi.js':
            response.headers[
                'Content-Type'] = 'application/javascript; charset=UTF-8'
            response.headers['Expires'] = (
                datetime.datetime.utcnow() +
                datetime.timedelta(days=self.__caching_days)
            ).strftime('%a, %d %b %Y %H:%M:%S GMT')
            return template(filename, template_lookup=[root])

        staticfile = static_file(filename, root=root)
        if isinstance(staticfile, HTTPError):
            return staticfile

        if 'webcam' == root:
            staticfile.add_header(
                'Expires',
                datetime.datetime.utcnow().strftime(
                    '%a, %d %b %Y %H:%M:%S GMT'))
        else:
            staticfile.add_header('Expires',
                                  (datetime.datetime.utcnow() +
                                   datetime.timedelta(days=self.__caching_days)
                                   ).strftime('%a, %d %b %Y %H:%M:%S GMT'))

        if staticfile.get_header('Last-Modified') is not None:
            staticfile.add_header(
                'Etag',
                hashlib.md5(
                    staticfile.get_header('Last-Modified')).hexdigest())

        return staticfile

    def __player_commands(self, action):
        result = {
            'ok': False,
            'title': _('Error!'),
            'message': _('Player command could ot be executed!')
        }

        if 'start' == action:
            self.__terrariumEngine.audio_player_start()
        elif 'stop' == action:
            self.__terrariumEngine.audio_player_stop()
        elif 'volumeup' == action:
            self.__terrariumEngine.audio_player_volume_up()
            result = {
                'ok': True,
                'title': _('OK!'),
                'message': _('Player command executed!')
            }
        elif 'volumedown' == action:
            self.__terrariumEngine.audio_player_volume_down()
            result = {
                'ok': True,
                'title': _('OK!'),
                'message': _('Player command executed!')
            }
        elif 'mute' == action:
            pass
        elif 'unmute' == action:
            pass

        return result

    def __upload_audio_file(self):
        result = {
            'ok': False,
            'title': _('Error!'),
            'message': _('File is not uploaded!')
        }
        upload = request.files.get('file')
        try:
            upload.save(terrariumAudioPlayer.AUDIO_FOLDER)
            self.__terrariumEngine.reload_audio_files()
            result = {
                'ok': True,
                'title': _('Success!'),
                'message': _('File \'%s\' is uploaded' % (upload.filename, ))
            }
        except IOError, message:
            result['message'] = _('Duplicate file \'%s\'' %
                                  (upload.filename, ))

        return result
Example #48
0
import random
from bottle import Bottle, template, static_file, request, response, redirect, HTTPError, abort
import model
import session

app = Bottle()


@app.route('/')
def index(db):
    """Render the index page"""

    session.get_or_create_session(db)
    # fetch all product
    cursor = db.cursor()
    cursor.execute('SELECT name from products')
    rows = cursor.fetchall()
    count = len(rows)
    product = {}
    # initalize empty data
    for no in range(count):
        product[no] = []
    for no in range(count):
        product[no].append(model.product_get(db, no))
    info = {
        'title': 'The WT',
        'products': product,
        'number': count,
    }
    return template('index', info)
Example #49
0
    def start_server(self, server_adapter=None):
        """
        Sets up all the routes for the server and starts it.

        server_backend: bottle.ServerAdapter (default None)
            The server adapter to use. The default bottle.WSGIRefServer is used if none is given.
            WARNING: If given, this will over-ride the host-ip and port passed as parameters to this
            object.
        """
        application = Bottle()
        application.route(f"/{REGISTER_WORKER_ROUTE}",
                          method='POST', callback=self.add_and_register_worker)
        application.route(f"/{CHALLENGE_PHRASE_ROUTE}/<worker_id>",
                          method='GET', callback=self.worker_manager.get_challenge_phrase)
        application.route(f"/{RETURN_GLOBAL_MODEL_ROUTE}",
                          method='POST', callback=self.return_global_model)
        application.route(f"/{NOTIFY_ME_IF_GM_VERSION_UPDATED_ROUTE}",
                          method='POST', callback=self.notify_me_if_gm_version_updated)
        application.route(f"/{RECEIVE_WORKER_UPDATE_ROUTE}/<worker_id>",
                          method='POST', callback=self.receive_worker_update)

        application.add_hook('after_request', self.enable_cors)

        # Admin routes
        application.get(
            f"/{WORKERS_ROUTE}", callback=auth_basic(self.is_admin)(self.admin_list_workers))
        application.post(
            f"/{WORKERS_ROUTE}", callback=auth_basic(self.is_admin)(self.admin_add_worker))
        application.delete(f"/{WORKERS_ROUTE}/<worker_id>",
                           callback=auth_basic(self.is_admin)(self.admin_delete_worker))
        application.put(f"/{WORKERS_ROUTE}/<worker_id>",
                        callback=auth_basic(self.is_admin)(self.admin_set_worker_status))

        if server_adapter is not None and isinstance(server_adapter, ServerAdapter):
            self.server_host_ip = server_adapter.host
            self.server_port = server_adapter.port
            run(application, server=server_adapter, debug=self.debug, quiet=True)
        elif self.ssl_enabled:
            run(application,
                host=self.server_host_ip,
                port=self.server_port,
                server='gunicorn',
                worker_class='gevent',
                keyfile=self.ssl_keyfile,
                certfile=self.ssl_certfile,
                debug=self.debug,
                timeout=60*60*24,
                quiet=True)
        else:
            run(application,
                host=self.server_host_ip,
                port=self.server_port,
                server='gunicorn',
                worker_class='gevent',
                debug=self.debug,
                timeout=60*60*24,
                quiet=True)
Example #50
0
import os

import tmdbsimple
from bottle import Bottle

from interfaces.cacheManager import CacheManager, ONE_MONTH

LANGUAGE = os.environ['LANGUAGE']
FILTERS = {
    'upcoming': tmdbsimple.Movies().upcoming,
    'top': tmdbsimple.Movies().top_rated,
    'popular': tmdbsimple.Movies().popular,
    'now-playing': tmdbsimple.Movies().now_playing,
}

movie_app = Bottle()


@movie_app.get('/movies/<uid:int>')
def movie_retrieve(uid, rdb):
    cache_manager = CacheManager(rdb, f'movie-{uid}', ONE_MONTH)

    return cache_manager.get_or_set(
        tmdbsimple.Movies(uid).info,
        language=LANGUAGE,
        append_to_response='credits,keywords,videos,reviews,images')


@movie_app.get(
    f"/movies/<filter_option:re:{'|'.join(FILTERS.keys())}>/<page:int>")
def movie_filter(filter_option, page):
Example #51
0
from bottle import Bottle, route, request, run, template, response
from bottle.ext import sqlalchemy
from sqlalchemy import create_engine, Column, Integer, Unicode
from sqlalchemy.ext.declarative import declarative_base
from random import randint
import sys
from operator import attrgetter, itemgetter
from functools import partial

try:
    import ujson as json
except ImportError:
    import json

app = Bottle()
app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@DBHOSTNAME:3306/hello_world?charset=utf8'
Base = declarative_base()
db_engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
plugin = sqlalchemy.Plugin(
    db_engine,
    keyword='db',
)
app.install(plugin)

if sys.version_info[0] == 3:
    xrange = range


class World(Base):
    __tablename__ = "World"
Example #52
0
from bottle import Bottle, template
import pyautogui

pyautogui.PAUSE = 1.5  # 每个函数执行后停顿1.5秒
pyautogui.FAILSAFE = True  # 鼠标移到左上角会触发FailSafeException,因此快速移动鼠标到左上角也可以停止

app = Bottle()


@app.route('/')
def index():
    return template("./index.html")


@app.route("/page_up")
def page_up():
    pyautogui.press('pageup')
    return {"msg": 1}


@app.route("/page_down")
def page_down():
    pyautogui.press('pagedown')
    return {"msg": 2}


app.run(host="0.0.0.0", port=8089)
Example #53
0
# -*- coding: utf-8 -*-
from bottle import Bottle, jinja2_view, post, request, redirect
from ..models.Auxiliar import Auxiliar, compare

# -------------- Controle das views de comparação
cl_compare = Bottle(True)
"""
### --------------  Página de Comparação -------------- ###
"""


# -------------- Página: Comparação
@cl_compare.route('/compare')
@jinja2_view('sistema/comparacao.html')
def comparacao():
    return dict(title='Comparação')


# -------------- Post: Comparação
@cl_compare.post('/compare')
@jinja2_view('out/compare.html')
def upload_conparacao():
    auxiliar = Auxiliar()
    pasta = auxiliar.comparacao

    arquivo_0 = request.files.get('arquivo_0')
    arquivo_1 = request.files.get('arquivo_1')

    chave_0 = auxiliar.upload_um_arquivo(arquivo_0, pasta)
    chave_1 = auxiliar.upload_um_arquivo(arquivo_1, pasta)
Example #54
0
from bottle import Bottle, static_file, request, response, run, HTTPError
import os
import json

from jsonmodel import JSONModelPlugin

app = Bottle()

_allow_origin = '*'
#_allow_methods = 'PUT, GET, POST, DELETE, OPTIONS'
_allow_methods = '*'

#_allow_headers = 'Authorization, Origin, Accept, Content-Type, X-Requested-With'
_allow_headers = '*'


@app.hook('after_request')
def enable_cors():
    '''Add headers to enable CORS'''

    response.headers['Access-Control-Allow-Origin'] = _allow_origin
    response.headers['Access-Control-Allow-Methods'] = _allow_methods
    response.headers['Access-Control-Allow-Headers'] = _allow_headers


def url(path):

    return 'http://' + request.urlparts[1] + path


@app.route('/')
Example #55
0
import bottle
from bottle import route, request, get, post, response, static_file, error, delete, Bottle, default_app
import datetime
import json
import sqlite3
import re

# create apps 1 and 2
defaultApp = default_app()
userApp = Bottle()

defaultApp.mount("/users", userApp)
#app2.mount('/timeline/', userApp)

userApp.config.load_config('./etc/microservice.ini')


# Allow JSON values to be loaded from app.config[key]
#
def json_config(key):
    value = userApp.config[key]
    return json.loads(value)


dbserver = json_config('dbserver.dblinks')

# set up DB connection
connUsers = sqlite3.connect(dbserver['users'])


# helper function for Divya
Example #56
0
from toughradius.console.libs.paginator import Paginator
from toughradius.console.libs import utils
from toughradius.console.websock import websock
from toughradius.console import models
from toughradius.console.base import *
from toughradius.console.admin import node_forms
from hashlib import md5
from twisted.python import log
import bottle
import datetime
import json
import functools

__prefix__ = "/node"

app = Bottle()
app.config['__prefix__'] = __prefix__

###############################################################################
# node manage
###############################################################################


@app.get('/', apply=auth_opr)
def node(db, render):
    return render("sys_node_list",
                  page_data=get_page_data(db.query(models.SlcNode)))


permit.add_route("/node", u"区域信息管理", u"系统管理", is_menu=True, order=1)
Example #57
0
def dummy_xmlrpc_app():
    app = Bottle()
    return app
Example #58
0
from bottle import Bottle, request, run
from truckpad.bottle.cors import CorsPlugin, enable_cors

app = Bottle()


@app.get('/')
def index():
    """
    CORS is disabled for this route
    """
    return "cors is disabled here"


@enable_cors
@app.post('/endpoint_1')
def endpoint_1():
    """
    CORS is enabled for this route. 
    OPTIONS requests will be handled by the plugin itself
    """
    print('Cors Enabled')
    return "cors is enabled, OPTIONS handled by plugin"


@enable_cors
@app.route('/endpoint_2', method=['GET', 'POST', 'OPTIONS'])
def endpoint_2():
    """
    CORS is enabled for this route. 
    OPTIONS requests will be handled by *you*
Example #59
0
from gevent import monkey
monkey.patch_all()

import getopt
import sys
from gevent.pool import Pool
from gevent.pywsgi import WSGIServer
from bottle import Bottle

addr, port = '127.0.0.1', 8898
opts, _ = getopt.getopt(sys.argv[1:], "b:")
for opt, value in opts:
    if opt == '-b':
        addr, port = value.split(":")

app = Bottle()
pool = Pool(256)
server = WSGIServer((addr, int(port)), app, spawn=pool)
server.backlog = 256
server.max_accept = 30000
print('ok')
server.serve_forever()
Example #60
0
    def __init__(self, themedir, siteconftemplate):
        self.installdir = sys.path[
            0]  # Note: this should ideally be gotten from somewhere else.
        self.wsgiapp = Bottle()
        self.apiclass = sandbox.csg2api(self.wsgiapp, self.runningsessions)

        # Parse arguments
        argparser = argparse.ArgumentParser()
        argparser.add_argument('sitesfolder',
                               metavar='<site storage folder>',
                               help="path to the folder containing sites")
        argparser.add_argument('siteroot',
                               metavar='<site name>',
                               help="site name/the folder with config.json")
        self.parsedargs = argparser.parse_args()

        # Setup configuration and path to site
        self.sitepath = os.path.abspath(
            os.path.join(self.parsedargs.sitesfolder,
                         self.parsedargs.siteroot))
        siteconffile = open(os.path.join(self.sitepath, "config.json"),
                            mode="rt",
                            encoding="utf-8")
        self.siteconf = configman.normalize_config(json.load(siteconffile),
                                                   self.parsedargs.siteroot)
        siteconffile.close()

        # Setup theming
        themesroot = os.path.abspath(themedir)
        self.themepath = os.path.join(themesroot,
                                      self.siteconf["site"]["theme"])
        os.chdir(self.sitepath)

        # Assign routes (done before the site code to allow overrides)
        # This is functionally equivalent of what the language does, but makes sure Bottle will call the right instance.
        self.getrandstaticredirect = self.wsgiapp.route(
            "/rand/<filepath:path>")(self.getrandstaticredirect)
        self.getstatic = self.wsgiapp.route("/static/<filepath:path>")(
            self.getstatic)
        self.compilethemesass = self.wsgiapp.route("/theme/sass/master.scss")(
            self.compilethemesass)
        self.getthemeasset = self.wsgiapp.route(
            "/theme/static/<filepath:path>")(self.getthemeasset)
        self.compilesass = self.wsgiapp.route("/sass/<filename:re:.*\.scss>")(
            self.compilesass)
        self.catchall = self.wsgiapp.route("/")(
            self.wsgiapp.route("/<filepath:path>")(view(
                os.path.join(self.themepath, "master.tpl"))(self.catchall)))
        self.dologin = self.wsgiapp.route("/login",
                                          method="POST")(self.dologin)

        # If they have code, run it
        if "additional_code" in self.siteconf["site"]:
            oldpath = sys.path
            sys.path[0] = self.sitepath
            importlib.invalidate_caches()
            with open(os.path.join(self.sitepath,
                                   self.siteconf["site"]["additional_code"]),
                      mode="rt") as codefile:
                sandbox.create_box(
                    codefile.read(), self.wsgiapp, apiclass=self.apiclass
                )  # This file is excempt from the linking clauses in the license, allowing it to be non-(A)GPL.
            sys.path = oldpath
            importlib.invalidate_caches()

        # Configure Nginx
        socketpath = "/tmp/csg2_{}.sock".format(
            self.siteconf["site"]["domain_name"].replace(".", "_"))
        print("-> Generating config.")
        with open(os.path.abspath(siteconftemplate),
                  mode="rt",
                  encoding="utf-8") as sitetemplate:
            sitetemplatetxt = sitetemplate.read()
            newsite = sitetemplatetxt.replace(
                "%%SERVERNAME%%",
                self.siteconf["site"]["domain_name"]).replace(
                    "%%SOCKETPATH%%", socketpath)
            with open("/tmp/{}.csg2nginx".format(
                    self.siteconf["site"]["domain_name"].replace(".", "_")),
                      mode="wt",
                      encoding="utf-8") as newconf:
                newconf.write(newsite)

        # Serve site.
        print("-> Serving up site on '{}'.".format(socketpath))
        waitress_serve(self.wsgiapp, unix_socket=socketpath)