コード例 #1
0
def hoitovuorot():
    """Jaa ja näytä hoitovuorot. Jakaa hoitovuorot ainoastaan niiden 
       lukumäärän perusteella. Voisi tehdä myös keston perusteella mutta 
       käyntien kestot ovat pääsääntöisesti lyhyitä joten paikasta toiseen 
       kulkemisen viemä aika on huomattava.
    """
    loginVaaditaan()
    # jakaa hoitovuoron mahdollisista hoitajista aina sille, jolla on
    # vähiten käyntejä. Voisi jakaa ajan perusteella mutta käynnit
    # ovat lyhyitä verrattuna liikkumisaikaan
    hoitokerrat = {h: 0 for h in map(lambda h: h.nimi, app().hoitajat.kaikki())}
    hoitovuorot = {h: [] for h in map(lambda h: h.nimi, app().hoitajat.kaikki())}
    vaillaHoitajaa = []
    virheviesti = None

    for k in app().asiakkaat.kaikkiKaynnit():
        sopivat = app().hoitajat.haeSopivatKaynnilla(k.kayntiid)
        if not sopivat: #ei löytynyt sopivia hoitajia
            vaillaHoitajaa.append(k.asiakasnimi + ": " + str(k))
            continue
        hoitaja = min(sopivat, key=lambda k: hoitokerrat[k.nimi])
        hoitokerrat[hoitaja.nimi] += 1
        hoitovuorot[hoitaja.nimi].append(k)

    if vaillaHoitajaa:
        virheviesti = "Seuraaville käynneille ei lyötynyt hoitajaa: " + "; ".join(vaillaHoitajaa)
    return template("hoitovuorot", hoitajat=hoitovuorot, virheviesti=virheviesti)
コード例 #2
0
def hoitajat():
    """Hoitajien hallintasivu"""
    loginVaaditaan()
    virheviesti = virheViesti()
    hoitsut = app().hoitajat.kaikki()
    luvat = app().vakiot.luvat()
    return template("hoitajat", hoitajat=hoitsut, luvat=luvat, virheviesti=virheviesti)
コード例 #3
0
    def get_middleware_app(self):
        if not self._auth_method:
            return None

        if not self._multi_tenancy:
            return None

        # keystone middleware is needed for fetching objects

        # app = bottle.app()
        app = AuthPostKeystone(bottle.app(), {'auth_svc': self})

        auth_middleware = auth_token.AuthProtocol(app, self._conf_info)
        self._auth_middleware = auth_middleware
        while True:
            try:
                self._auth_token = auth_middleware.get_admin_token()
                break
            except auth_token.ServiceError as e:
                self._server_mgr.config_log_error(
                    "Error in getting admin token: " + str(e))
                time.sleep(2)

        # open access for troubleshooting
        self._open_app = AuthOpen('127.0.0.1', '8095', bottle.app())
        gevent.spawn(self._open_app.start_http_server)

        app = auth_middleware

        # allow multi tenancy to be updated dynamically
        app = AuthPreKeystone(auth_middleware,
                              {'admin_token': self._auth_token},
                              self._multi_tenancy)

        return app
コード例 #4
0
    def get_middleware_app(self):
        if not self._auth_method:
            return None

        if not self._multi_tenancy:
            return None

        # keystone middleware is needed for fetching objects

        # app = bottle.app()
        app = AuthPostKeystone(bottle.app(), {'auth_svc': self})

        auth_middleware = auth_token.AuthProtocol(app, self._conf_info)
        self._auth_middleware = auth_middleware

        # open access for troubleshooting
        admin_port = self._conf_info['admin_port']
        self._local_auth_app = LocalAuth(bottle.app(), self._conf_info)
        vnc_greenlets.VncGreenlet("VNC Auth Keystone", self._local_auth_app.start_http_server)

        app = auth_middleware

        # allow multi tenancy to be updated dynamically
        app = AuthPreKeystone(
            auth_middleware,
            None,
            self._multi_tenancy)

        return app
コード例 #5
0
ファイル: test_securecookies.py プロジェクト: SteakKing/code
 def testWithBottle(self):
     bottle.app.push()
     bottle.response.bind(bottle.app())
     bottle.response.set_cookie('key', dict(value=5), secret=tob('1234'))
     cheader = [v for k, v in bottle.response.wsgiheader() if k == 'Set-Cookie'][0]
     bottle.request.bind({'HTTP_COOKIE': cheader.split(';')[0]}, bottle.app())
     self.assertEqual(repr(dict(value=5)), repr(bottle.request.get_cookie('key', secret=tob('1234'))))
     bottle.app.pop()
コード例 #6
0
    def __call__(self, env, start_response):
        if (env.get('PATH_INFO') and
            env['PATH_INFO'].startswith('/documentation')):
            app = bottle.app()
        else:
            app = self.app if self.mt else bottle.app()

        return app(env, start_response)
コード例 #7
0
def poistaKaynti():
    kayntiId = request.forms.getunicode("kayntiid")
    asiakasId = request.forms.getunicode("asiakasid")
    if kayntiId:
        app().asiakkaat.poistaKaynti(kayntiId)
    if asiakasId:
        app().asiakkaat.poistaAsiakas(asiakasId)
    redirect("/asiakkaanHallinta")
コード例 #8
0
def login_post():
    name = request.forms.getunicode("name")
    password = request.forms.getunicode("password")
    
    try:
        app().auth.login(name, password)
    # Innokas except jottei loginin epäonnistumisviesti anna vihjeitä hyökkääjälle
    except Exception:
        asetaVirheViesti("Kirjautuminen epäonnistui")
        redirect("/login")
    redirect("/")
コード例 #9
0
def hoitajat_post():
    loginVaaditaan()
    nimi = request.forms.getunicode("nimi")
    luvat = request.forms.getall("lupa")
    # ei ole getallunicode()-metodia, muuta kaikki unicodeksi
    luvat = [l.encode("latin-1").decode("utf8") for l in luvat]
    try:
        app().hoitajat.uusi(nimi, luvat)
    except Exception:
        asetaVirheViesti("Hoitajan lisäys epäonnistui")
        redirect("/hoitajat")
    redirect("/hoitajat")
コード例 #10
0
def asiakkaat_post():
    """Luo uusi asiakas"""
    loginVaaditaan()
    nimi = request.forms.getunicode("nimi")
    if not nimi:
        asetaVirheViesti("Asiakkaalla tulee olla nimi")
        redirect("asiakkaanHallinta")
    try:
        app().asiakkaat.uusi(nimi)
    except Exception:
        asetaVirheViesti("Asiakkaan lisäys epäonnistui")
    redirect("/asiakkaanHallinta")
コード例 #11
0
def asiakkaanHallinta():
    """Asiakkaiden hallintasivu"""
    virheviesti = virheViesti()

    loginVaaditaan()
    asiakkaat = app().asiakkaat.kaikki()
    luvat = app().vakiot.luvat()
    paivat = app().vakiot.paivat()
    ajat = app().vakiot.ajat()
    kestot = app().vakiot.kestot()
    return template("asiakkaanHallinta", asiakkaat=asiakkaat, luvat=luvat, ajat=ajat, 
                    kestot=kestot, paivat=paivat, virheviesti=virheviesti)
コード例 #12
0
ファイル: __init__.py プロジェクト: CZ-NIC/foris
def foris_403_handler(error):
    if isinstance(error, CSRFValidationError):
        try:
            # maybe the session expired, if so, just redirect the user
            redirect_unauthenticated()
        except bottle.HTTPResponse as e:
            # error handler must return the exception, otherwise it would
            # be raised and not handled by Bottle
            return e

    # otherwise display the standard error page
    bottle.app().default_error_handler(error)
コード例 #13
0
def register_post():
    name = request.forms.getunicode("name")
    password1 = request.forms.getunicode("password1")
    password2 = request.forms.getunicode("password2")
    
    if password1 != password2:
        asetaVirheViesti("Salasanat eivät täsmää")
        redirect("/register")
    try:
        app().auth.register(name, password1)
    except IntegrityError:
        asetaVirheViesti("Valitsemasi käyttäjätunnus on jo käytössä")
        redirect("/register")
    return template("rekOK")
コード例 #14
0
    def test_1_2_plugins(self):
        print ''
        print 'test plugins'

        print 'plugins count:', self.alignak_webui.plugins_count
        for plugin in self.alignak_webui.plugins:
            print "Plugin:", plugin

        print 'get plugins routes - route name is present'
        for s_route in [r for r in bottle.app().routes if r.name]:
            print "Plugin route:", s_route.name, s_route.rule, s_route.callback

        print 'get plugins static files routes - rule starts with /plugins'
        for s_route in [r for r in bottle.app().routes if r.rule.startswith('/plugins')]:
            print "Plugin static files route:", s_route.rule
コード例 #15
0
ファイル: test_wsgi.py プロジェクト: al3xandru/bottle
 def test_503(self):
     """ WSGI: Server stopped (HTTP 503) """
     @bottle.route('/')
     def test(): return 'bla'
     self.assertStatus(200, '/')
     bottle.app().serve = False
     self.assertStatus(503, '/')
コード例 #16
0
ファイル: __init__.py プロジェクト: CZ-NIC/foris
def static(filename):
    """ return static file
    :param filename: url path
    :type filename: str
    :return: http response
    """

    def prepare_response(filename, fs_root):
        response = bottle.static_file(filename, root=fs_root)
        response.add_header("Cache-Control", "public, max-age=31536000")
        return response

    if not bottle.DEBUG:
        logger.warning("Static files should be handled externally in production mode.")

    match = re.match(r"/*plugins/+(\w+)/+(.+)", filename)
    if match:
        plugin_name, plugin_file = match.groups()

        # find correspoding plugin
        for plugin in bottle.app().foris_plugin_loader.plugins:
            if plugin.PLUGIN_NAME == plugin_name:
                return prepare_response(plugin_file, os.path.join(plugin.DIRNAME, "static"))

        return bottle.HTTPError(404, "File does not exist.")

    match = re.match(r"/*generated/+([a-z]{2})/+(.+)", filename)
    if match:
        filename = "/".join(match.groups())
        return prepare_response(
            filename, os.path.join(current_state.assets_path, current_state.app)
        )

    return prepare_response(filename, os.path.join(BASE_DIR, "static"))
コード例 #17
0
def startServer():
    import bottle

    app = bottle.default_app()  # create bottle app

    loadErrors(app)
    loadWebUI(app)

    app = bottle.app()

    session_opts = {
        'session.type': 'file',
        'session.cookie_expires': 9000,
        'session.data_dir': 'data',
        'session.auto': True
    }

    app = SessionMiddleware(app, session_opts)

    bottle.run(app=app,
               server='paste',
               host="0.0.0.0",
               port=8030,
               debug=True,
               interval=1,
               quiet=False)
コード例 #18
0
ファイル: webui.py プロジェクト: dgpreatoni/mdig
def start_web_service():
    change_to_web_mapset()
    rt.start()
    mdig_worker_process.start()

    # setup and run webapp
    global app
    app = bottle.app()
    app.catchall = False
    try:
        import paste.evalexception
        myapp = paste.evalexception.middleware.EvalException(app)
    except ImportError:
        myapp = app
    myapp = RestoreMapset(myapp)
    c = config.get_config()
    # Don't check replicates are complete, since this will make the web service
    # too slow if there are lots of replicates
    if "replicate" not in c:
        c["replicate"] = {}
    c["replicate"]["check_complete"] = "false"
    # for testing ports available in windows
    # c["WEB"]["port"] = 8080
    bottle.run(app=myapp, host=c["WEB"]["host"], port=int(
        c["WEB"]["port"]), reloader=reloader)
コード例 #19
0
def application(environ, start_response):
    try:
        application = bottle.app()
        application.catchall = False
        application = JsonApiMiddleware(application)
        return application(environ, start_response)

    except:
        rollbar.report_exc_info(sys.exc_info(), webob.Request(environ))

        # Bare bones 500 handler
        content = b""
        if environ.get("JSON"):
            content = '{"__status_code__": 500}'
            content_type = "application/json; charset=UTF-8"
        else:
            dirname = os.path.dirname(__file__)
            five_hundred_path = os.path.join(dirname, "app/html/five_hundred.html")
            with open(five_hundred_path, "r", encoding="utf-8") as f:
                content = f.read()
            content_type = "text/html; charset=UTF-8"
        content = content.encode("utf-8")
        start_response(
            "500 Internal Server Error",
            [("Content-Type", content_type), ("Content-Length", str(len(content)))],
            sys.exc_info(),
        )
        environ["wsgi.errors"] = content
        return [content]
コード例 #20
0
    def setUp(self):
        super(TestCase, self).setUp()
        global cov_handle
        if not cov_handle:
            cov_handle = coverage.coverage(source=['./'], omit=['.venv/*'])
        #cov_handle.start()

        cfgm_common.zkclient.LOG_DIR = './'
        gevent.wsgi.WSGIServer.handler_class = FakeWSGIHandler
        setup_common_flexmock()

        self._api_server_ip = socket.gethostbyname(socket.gethostname())
        self._api_server_port = get_free_port()
        http_server_port = get_free_port()
        self._api_admin_port = get_free_port()
        self._api_svr_greenlet = gevent.spawn(launch_api_server,
                                     self.id(),
                                     self._api_server_ip, self._api_server_port,
                                     http_server_port, self._api_admin_port,
                                     self._config_knobs)
        block_till_port_listened(self._api_server_ip, self._api_server_port)
        extra_env = {'HTTP_HOST':'%s%s' %(self._api_server_ip,
                                          self._api_server_port)}
        self._api_svr_app = TestApp(bottle.app(), extra_environ=extra_env)
        self._vnc_lib = VncApi('u', 'p', api_server_host=self._api_server_ip,
                               api_server_port=self._api_server_port)

        FakeNovaClient.vnc_lib = self._vnc_lib
        self._api_server_session = requests.Session()
        adapter = requests.adapters.HTTPAdapter()
        self._api_server_session.mount("http://", adapter)
        self._api_server_session.mount("https://", adapter)
        self._api_server = vnc_cfg_api_server.server
        self._api_server._sandesh.set_logging_level(level="SYS_DEBUG")
        self.addCleanup(self.cleanUp)
コード例 #21
0
    def setUp(self):
        super(TestCase, self).setUp()
        global cov_handle
        if not cov_handle:
            cov_handle = coverage.coverage(source=['./'], omit=['.venv/*'])
        cov_handle.start()
        setup_flexmock()

        api_server_ip = socket.gethostbyname(socket.gethostname())
        api_server_port = get_free_port()
        http_server_port = get_free_port()
        self._web_host = api_server_ip
        self._web_port = api_server_port
        self._api_svr_greenlet = gevent.spawn(launch_api_server,
                                     api_server_ip, api_server_port,
                                     http_server_port)
        block_till_port_listened(api_server_ip, api_server_port)
        extra_env = {'HTTP_HOST':'%s%s' %(api_server_ip,
                                          api_server_port)}
        self._api_svr_app = TestApp(bottle.app(), extra_environ=extra_env)
        #FakeRequestsSession._api_svr_app = self._api_svr_app
        
        self._vnc_lib = VncApi('u', 'p', api_server_host=api_server_ip,
                               api_server_port=api_server_port)

        self._api_server_session = requests.Session()
        adapter = requests.adapters.HTTPAdapter()
        self._api_server_session.mount("http://", adapter)
        self._api_server_session.mount("https://", adapter)
        self._api_server = vnc_cfg_api_server.server
        self._api_server._sandesh.set_logging_params(level="SYS_WARN")
コード例 #22
0
ファイル: monacos_decider.py プロジェクト: M425/Monacos
def start():
    """ Start the decider
    """
    host = cc.conf['decider']['host']
    managers = cc.conf['compute']['managers']
    whoami = cc.conf['whoami']

    port = None
    for m in managers:
        if m['realhost'] == whoami:
            port = m['decider_port']
    ipc.set('self_port', port)

    hostlist = []
    for m in managers:
        if m['realhost'] != whoami:
            hostlist.append(m)
    ipc.set('hostlist', json.dumps(hostlist))

    bottle.debug(True)
    app = bottle.app()
    app.state = {
        'machine': state_machine.get_machine()
    }
    app.error_handler = aux.bottle_errors.ERRORS_HANDLERS

    log_api.info('Starting the decider, listening to %s:%s, pid:%s',
                 host, port, str(os.getpid()))
    quiet = cc.conf['decider']['log']['level'] != "DEBUG"
    bottle.run(host=host, port=port,
               quiet=quiet, reloader=cc.conf['development'])
コード例 #23
0
ファイル: monacos_decider.py プロジェクト: M425/Monacos
def bottle_underload():
    machine = bottle.app().state['machine']
    log_api.info('RECV: Underload')
    return 'Notification received'
    # retrieve body
    try:
        data = json.load(bottle.request.body)
    except ValueError:
        log_api.error('Retrieving: ValueError')
        raise HTTPError(400)
    # validate the data
    try:
        parser.validate(machine.whoami_host, data)
    except KeyError:
        log_api.error('Validating: KeyError')
        raise HTTPError(400)
    except exc.NotMyAlarm:
        log_api.error('Validating: NotMyAlarm')
        raise HTTPError(400)
    # execute data
    try:
        machine.underload()
    except transitions.MachineError:
        log.error('Machine: MachineError, state=%s' % machine.state)
        raise HTTPError(409)
    return 'Notification received'
コード例 #24
0
ファイル: RouteLoader.py プロジェクト: apuignav/WebAPIDIRAC
def loadRoutes():
  routesPath = os.path.join( DIRAC.rootPath, "WebAPIDIRAC", "WebAPISystem", "private", "routes" )
  lastRoutesLoaded = 0
  for fileName in os.listdir( routesPath ):
    match = gRoutesRE.match( fileName )
    if match:
      pythonClass = match.groups()[0]
      objPythonPath = "WebAPIDIRAC.WebAPISystem.private.routes.%s" % pythonClass
      try:
        objModule = __import__( objPythonPath,
                                globals(),
                                locals(), pythonClass )
      except:
        DIRAC.gLogger.exception( "Could not load %s" % fileName )
      routesLoaded = 0
      rules = bottle.app().router.rules
      for rule in rules:
        for method in rules[ rule ]:
          routesLoaded += 1
      routesLoaded -= lastRoutesLoaded
      DIRAC.gLogger.info( "Loaded %s routes for %s" % ( routesLoaded, pythonClass ) )
      lastRoutesLoaded += routesLoaded
      if 'initialize' in dir( objModule ):
        DIRAC.gLogger.notice( "Initializing %s" % pythonClass )
        getattr( objModule, 'initialize' )()
コード例 #25
0
ファイル: manager.py プロジェクト: fr34k8/openstack-neat
def service():
    params = get_params(bottle.request)
    state = bottle.app().state
    validate_params(state['state']['hashed_username'],
                    state['state']['hashed_password'],
                    params)
    log.info('Received a request from %s: %s',
             get_remote_addr(bottle.request),
             str(params))
    try:
        if params['reason'] == 0:
            log.info('Processing an underload of a host %s', params['host'])
            execute_underload(
                state['config'],
                state['state'],
                params['host'])
        else:
            log.info('Processing an overload, VMs: %s', str(params['vm_uuids']))
            execute_overload(
                state['config'],
                state['state'],
                params['host'],
                params['vm_uuids'])
    except:
        log.exception('Exception during request processing:')
        raise
コード例 #26
0
ファイル: test_wsgi.py プロジェクト: Alexis-D/bottle
 def test_basicmounting(self):
     bottle.app().mount(self.subapp, '/test')
     self.assertStatus(404, '/')
     self.assertStatus(404, '/test')
     self.assertStatus(404, '/test/')
     self.assertStatus(404, '/test/test/bar')
     @self.subapp.route('/')
     @self.subapp.route('/test/:test')
     def test(test='foo'):
         return test
     self.assertStatus(404, '/')
     self.assertStatus(404, '/test')
     self.assertStatus(200, '/test/')
     self.assertBody('foo', '/test/')
     self.assertStatus(200, '/test/test/bar')
     self.assertBody('bar', '/test/test/bar')
コード例 #27
0
ファイル: manager.py プロジェクト: fr34k8/openstack-neat
def start():
    """ Start the global manager web service.
    """
    config = read_and_validate_config([DEFAILT_CONFIG_PATH, CONFIG_PATH],
                                      REQUIRED_FIELDS)

    common.init_logging(
        config['log_directory'],
        'global-manager.log',
        int(config['log_level']))

    state = init_state(config)
    switch_hosts_on(state['db'],
                    config['ether_wake_interface'],
                    state['host_macs'],
                    state['compute_hosts'])

    bottle.debug(True)
    bottle.app().state = {
        'config': config,
        'state': state}

    host = config['global_manager_host']
    port = config['global_manager_port']
    log.info('Starting the global manager listening to %s:%s', host, port)
    bottle.run(host=host, port=port)
コード例 #28
0
def main(argv=None):
    """Main Block - Configure and run the Bottle Web Server."""
    cmd_opts = parse_cmdline(argv)[0]
    if cmd_opts.confpath is not None:
        if os.path.exists(cmd_opts.confpath):
            conf_paths = [cmd_opts.confpath,]
        else:
            return "Configuration file not found: %s" % cmd_opts.confpath
    else:
        conf_paths = [os.path.join(path, defaultConfFilename) 
                      for path in ('/etc', '.',)]
    try:
        conf.update(parse_conf_files(conf_paths))
    except ConfigurationError:
        return(sys.exc_info()[1])
    if cmd_opts.bindport is not None:
        conf['bindport'] = cmd_opts.bindport
    if cmd_opts.bindaddr is not None:
        conf['bindaddr'] = cmd_opts.bindaddr
    if cmd_opts.baseurl is not None:
        conf['baseurl'] = cmd_opts.baseurl
    if cmd_opts.devel:
        from bottle import debug
        debug(True)
    app = SessionMiddleware(bottle.app(), sessionOpts)
    bottle.run(app=app, host=conf['bindaddr'], port=conf['bindport'], 
               reloader=cmd_opts.devel)
コード例 #29
0
def create_api_server_instance(test_id, config_knobs):
    ret_server_info = {}
    allocated_sockets = []
    ret_server_info['ip'] = socket.gethostbyname(socket.gethostname())
    ret_server_info['service_port'] = get_free_port(allocated_sockets)
    ret_server_info['introspect_port'] = get_free_port(allocated_sockets)
    ret_server_info['admin_port'] = get_free_port(allocated_sockets)
    ret_server_info['allocated_sockets'] = allocated_sockets
    ret_server_info['greenlet'] = gevent.spawn(launch_api_server,
        test_id, ret_server_info['ip'], ret_server_info['service_port'],
        ret_server_info['introspect_port'], ret_server_info['admin_port'],
        config_knobs)
    block_till_port_listened(ret_server_info['ip'],
        ret_server_info['service_port'])
    extra_env = {'HTTP_HOST': ret_server_info['ip'],
                 'SERVER_PORT': str(ret_server_info['service_port'])}
    ret_server_info['app'] = TestApp(bottle.app(), extra_environ=extra_env)
    ret_server_info['api_conn'] = VncApi('u', 'p',
        api_server_host=ret_server_info['ip'],
        api_server_port=ret_server_info['service_port'])

    FakeNovaClient.vnc_lib = ret_server_info['api_conn']
    ret_server_info['api_session'] = requests.Session()
    adapter = requests.adapters.HTTPAdapter()
    ret_server_info['api_session'].mount("http://", adapter)
    ret_server_info['api_session'].mount("https://", adapter)
    ret_server_info['api_server'] = vnc_cfg_api_server.server
    ret_server_info['api_server']._sandesh.set_logging_level(level="SYS_DEBUG")

    return ret_server_info
コード例 #30
0
    def setUp(self):
        super(TestCase, self).setUp()
        global cov_handle
        if not cov_handle:
            cov_handle = coverage.coverage(source=["./"], omit=[".venv/*"])
        cov_handle.start()

        cfgm_common.zkclient.LOG_DIR = "./"
        gevent.wsgi.WSGIServer.handler_class = FakeWSGIHandler
        setup_common_flexmock()

        self._api_server_ip = socket.gethostbyname(socket.gethostname())
        self._api_server_port = get_free_port()
        http_server_port = get_free_port()
        self._api_admin_port = get_free_port()
        self._api_svr_greenlet = gevent.spawn(
            launch_api_server,
            self._api_server_ip,
            self._api_server_port,
            http_server_port,
            self._api_admin_port,
            self._config_knobs,
        )
        block_till_port_listened(self._api_server_ip, self._api_server_port)
        extra_env = {"HTTP_HOST": "%s%s" % (self._api_server_ip, self._api_server_port)}
        self._api_svr_app = TestApp(bottle.app(), extra_environ=extra_env)
        self._vnc_lib = VncApi("u", "p", api_server_host=self._api_server_ip, api_server_port=self._api_server_port)

        FakeNovaClient.vnc_lib = self._vnc_lib
        self._api_server_session = requests.Session()
        adapter = requests.adapters.HTTPAdapter()
        self._api_server_session.mount("http://", adapter)
        self._api_server_session.mount("https://", adapter)
        self._api_server = vnc_cfg_api_server.server
        self._api_server._sandesh.set_logging_params(level="SYS_WARN")
コード例 #31
0
        response.status = HttpStatus.Ok
        return result

    return endpoint


def hello_world():
    return "OUT!"


def t():
    return {"a": "b"}


api = app()

# api.install(CORSPlugin())

api.add_hook("after_request", cors)

api.route("/", "GET", hello_world)
api.route("/p", "POST", build_prediction_endpoint(resnet50))
api.route("/r50/p", "POST", build_prediction_endpoint(resnet50))
api.route("/r34/p", "POST", build_prediction_endpoint(resnet34))
api.route("/r34/vocab", "GET",
          lambda: {"vocab": [l for l in resnet34.vocab()]})
api.route("/r50/vocab", "GET",
          lambda: {"vocab": [l for l in resnet50.vocab()]})

api.run(port=5000)
コード例 #32
0
 def test_http_get_routes(self):
     """Test that session ids are not authenticated with non-post routes."""
     self.mock_database.sessions.find_one.return_value = None
     route = bottle.Route(bottle.app(), "/", "GET", self.route)
     self.assertEqual(self.success, route.call())
コード例 #33
0
    CLIENT_ID = client_secrets["web"]["client_id"]
    CLIENT_SECRET = client_secrets["web"]["client_secret"]
    SCOPE = client_secrets["web"][
        "auth_uri"]  #"https://accounts.google.com/o/oauth2/auth"
    REDIRECT_URI = client_secrets["web"]["redirect_uris"][0]
    GOOGLE_SCOPE = 'https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email'

# Configure the SessionMiddleware
session_opts = {
    'session.type': 'file',
    'session.cookie_expires': 300,
    'session.data_dir': './data',
    'session.auto': True
}
app = SessionMiddleware(
    bottle.app(), session_opts
)  # app is now a replacement of original bottle.app(); if not specified in run() at bottom, default app
scope = 'https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email'
"""@route('/home')
def login_page():

    flow = flow_from_clientsecrets("client_secret.json", scope, redirect_uri=redirect_uri_)
    uri = flow.step1_get_authorize_url()
    print "@login:redirecting to google"
    redirect(uri)
    return

@route('/redirect')
def login_done_redirect():
	global redirect_search_uri
	global user_email
コード例 #34
0
 def test_module_shortcuts_with_different_name(self):
     self.assertWraps(bottle.url, bottle.app().get_url)
コード例 #35
0
    def __init__(self, args):
        self._homepage_links = []
        self._args = args
        self.service_config = args.service_config
        self.cassandra_config = args.cassandra_config
        self._debug = {
            'hb_stray': 0,
            'msg_pubs': 0,
            'msg_subs': 0,
            'msg_query': 0,
            'msg_hbt': 0,
            'ttl_short': 0,
            'policy_rr': 0,
            'policy_lb': 0,
            'policy_fi': 0,
            'db_upd_hb': 0,
            'throttle_subs': 0,
            '503': 0,
            'count_lb': 0,
        }
        self._ts_use = 1
        self.short_ttl_map = {}
        self._sem = BoundedSemaphore(1)

        self._base_url = "http://%s:%s" % (self._args.listen_ip_addr,
                                           self._args.listen_port)
        self._pipe_start_app = None

        bottle.route('/', 'GET', self.homepage_http_get)

        # heartbeat
        bottle.route('/heartbeat', 'POST', self.api_heartbeat)

        # publish service
        bottle.route('/publish', 'POST', self.api_publish)
        self._homepage_links.append(
            LinkObject('action', self._base_url, '/publish',
                       'publish service'))
        bottle.route('/publish/<end_point>', 'POST', self.api_publish)

        # subscribe service
        bottle.route('/subscribe', 'POST', self.api_subscribe)
        self._homepage_links.append(
            LinkObject('action', self._base_url, '/subscribe',
                       'subscribe service'))

        # query service
        bottle.route('/query', 'POST', self.api_query)
        self._homepage_links.append(
            LinkObject('action', self._base_url, '/query', 'query service'))

        # collection - services
        bottle.route('/services', 'GET', self.show_all_services)
        self._homepage_links.append(
            LinkObject('action', self._base_url, '/services',
                       'show published services'))
        bottle.route('/services.json', 'GET', self.services_json)
        self._homepage_links.append(
            LinkObject('action', self._base_url, '/services.json',
                       'List published services in JSON format'))
        # show a specific service type
        bottle.route('/services/<service_type>', 'GET', self.show_all_services)

        # api to perform on-demand load-balance across available publishers
        bottle.route('/load-balance/<service_type>', 'POST',
                     self.api_lb_service)

        # update service
        bottle.route('/service/<id>', 'PUT', self.service_http_put)

        # get service info
        bottle.route('/service/<id>', 'GET', self.service_http_get)
        bottle.route('/service/<id>/brief', 'GET', self.service_brief_http_get)

        # delete (un-publish) service
        bottle.route('/service/<id>', 'DELETE', self.service_http_delete)

        # collection - clients
        bottle.route('/clients', 'GET', self.show_all_clients)
        bottle.route('/clients/<service_type>/<service_id>', 'GET',
                     self.show_all_clients)
        self._homepage_links.append(
            LinkObject('action', self._base_url, '/clients',
                       'list all subscribers'))
        bottle.route('/clients.json', 'GET', self.clients_json)
        self._homepage_links.append(
            LinkObject('action', self._base_url, '/clients.json',
                       'list all subscribers in JSON format'))

        # show config
        bottle.route('/config', 'GET', self.show_config)
        self._homepage_links.append(
            LinkObject('action', self._base_url, '/config',
                       'show discovery service config'))

        # show debug
        bottle.route('/stats', 'GET', self.show_stats)
        self._homepage_links.append(
            LinkObject('action', self._base_url, '/stats',
                       'show discovery service stats'))

        # cleanup
        bottle.route('/cleanup', 'GET', self.cleanup_http_get)
        self._homepage_links.append(
            LinkObject('action', self._base_url, '/cleanup',
                       'Purge inactive publishers'))

        if not self._pipe_start_app:
            self._pipe_start_app = bottle.app()

        # sandesh init
        self._sandesh = Sandesh()
        module = Module.DISCOVERY_SERVICE
        module_name = ModuleNames[module]
        node_type = Module2NodeType[module]
        node_type_name = NodeTypeNames[node_type]
        instance_id = self._args.worker_id
        disc_client = discovery_client.DiscoveryClient(
            '127.0.0.1', self._args.listen_port,
            ModuleNames[Module.DISCOVERY_SERVICE])
        self._sandesh.init_generator(
            module_name,
            socket.gethostname(),
            node_type_name,
            instance_id,
            self._args.collectors,
            'discovery_context',
            int(self._args.http_server_port), ['sandesh'],
            disc_client,
            logger_class=self._args.logger_class,
            logger_config_file=self._args.logging_conf)
        self._sandesh.set_logging_params(enable_local_log=self._args.log_local,
                                         category=self._args.log_category,
                                         level=self._args.log_level,
                                         file=self._args.log_file)
        self._sandesh.trace_buffer_create(name="dsHeartBeatTraceBuf",
                                          size=1000)

        # DB interface initialization
        self._db_connect(self._args.reset_config)

        # build in-memory subscriber data
        self._sub_data = {}
        for (client_id, service_type) in self._db_conn.subscriber_entries():
            self.create_sub_data(client_id, service_type)
コード例 #36
0
def log(ip, msg):
    print("[%s] (%s) %s" % (get_time_now(), ip, msg))
    return msg


def get_client_ip():
    x_forwarded_for = request.environ.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.environ.get('REMOTE_ADDR')
    return ip


app = app()

@app.get('/confirm/<uuid>')
def get_confirm(uuid):
    return """<html><body><p>If you're here, you were meant to click this link
    many months ago, and the page no longer exists.</p>
    
    <p>Please email [email protected] for further
    assistance.</p></body></html>"""

@app.get('/admin/update/<uuid>')
@app.get('/update/<uuid>')
@app.get('/update')
@app.get('/new')
@app.get('/')
def get_main(uuid=None):
コード例 #37
0
import bottle
from bottle import get, static_file
import requests
import json


@get("/css/<filepath:re:.*\.css>")
def css(filepath):
    return static_file(filepath, root="css/")


@get("/js/<filepath:re:.*\.js>")
def css(filepath):
    return static_file(filepath, root="js/")


@bottle.route("/")
@bottle.view("ipinfo.tpl")
def index():
    info = requests.get('http://ipinfo.io/')
    j = json.loads(info.text)
    return {"title": "IP informations", "ip": j['ip'], "country": j['country']}


bottle.run(bottle.app(), host='0.0.0.0', port=80, debug=True, reloader=True)
コード例 #38
0
ファイル: __init__.py プロジェクト: PaddyPat/pyload
    join(PYLOAD_DIR, "locale"),
    languages=[config.get("general", "language"), "en"],
    fallback=True)
translation.install(True)
env.install_gettext_translations(translation)

from beaker.middleware import SessionMiddleware

session_opts = {
    'session.type': 'file',
    'session.cookie_expires': False,
    'session.data_dir': './tmp',
    'session.auto': False
}

web = StripPathMiddleware(SessionMiddleware(app(), session_opts))
web = GZipMiddleWare(web)

if PREFIX:
    web = PrefixMiddleware(web, prefix=PREFIX)

import pyload.webui.app


def run_simple(host="0.0.0.0", port="8000"):
    run(app=web, host=host, port=port, quiet=True)


def run_lightweight(host="0.0.0.0", port="8000"):
    run(app=web, host=host, port=port, server="bjoern", quiet=True)
コード例 #39
0
# App
from ClinicalTrials.mngobject import MNGObject
from ClinicalTrials.trial import Trial
from ClinicalTrials.runner import Runner
from ClinicalTrials.umls import SNOMEDLookup

# bottle, beaker and Jinja setup
session_opts = {
    'session.type': 'file',
    'session.timeout': 3600,
    'session.cookie_expires': 3600,
    'session.data_dir': './session_data',
    'session.auto': True
}
app = application = SessionMiddleware(
    bottle.app(),
    session_opts)  # "application" is needed for some services like AppFog
_jinja_templates = Environment(loader=PackageLoader('wsgi', 'templates'),
                               trim_blocks=True)


# ------------------------------------------------------------------------------ Utilities
def _get_session():
    return bottle.request.environ.get('beaker.session')


# only used for SMART v0.6+
def _get_smart():
    if not USE_SMART:
        return None
コード例 #40
0
def bottle_patch(path=None, **options):
    """Convenience decorator of the same form as @get and @post in the
    Bottle module.
    """
    return app().route(path, 'PATCH', **options)
コード例 #41
0
ファイル: rest.py プロジェクト: sysbot/OpenClos
 def initRest(self):
     self.addRoutes(self.baseUrl)
     self.app = bottle.app()
コード例 #42
0
import tempfile
import json
import html
import yaml
import bcrypt
import requests
import shutil
from bottle import app, route, template, static_file, redirect, abort, request, response
from beaker.middleware import SessionMiddleware
from steam_buddy.config import PLATFORMS, SSH_KEY_HANDLER, AUTHENTICATOR, SETTINGS_HANDLER, STEAMGRID_HANDLER, FTP_SERVER, RESOURCE_DIR, BANNER_DIR, CONTENT_DIR, SHORTCUT_DIR, SESSION_OPTIONS
from steam_buddy.functions import load_shortcuts, sanitize, upsert_file, delete_file
from steam_buddy.auth_decorator import authenticate
from steam_buddy.platforms.epic_store import EpicStore
from steam_buddy.platforms.flathub import Flathub

server = SessionMiddleware(app(), SESSION_OPTIONS)

tmpfiles = {}

PLATFORM_HANDLERS = {
    "epic-store": EpicStore(),
    "flathub": Flathub(),
}


def authenticate_platform(platform):
    if platform in PLATFORM_HANDLERS:
        if not PLATFORM_HANDLERS[platform].is_authenticated():
            redirect('/platforms/{platform}'.format(platform=platform))
            return False
    return True
コード例 #43
0
 def __call__(self, env, start_response):
     app = self.app if self.mt else bottle.app()
     return app(env, start_response)
コード例 #44
0
ファイル: example.py プロジェクト: oz123/peewee-session
import bottle
import random
import string
import time

from bottle import request, response, HTTPResponse, template
from peewee_session import PeeweeSessionPlugin
from util import authenticator, generate_token

from peewee import SqliteDatabase

db = SqliteDatabase('test.db')

CONFIG = {'db': db}

app = bottle.app()
app.config.update(CONFIG)

session_plugin = PeeweeSessionPlugin(cookie_lifetime='10 seconds',
                                     db_conn=db,
                                     cookie_secret='very-s3kr3t-s4lt')

app.install(session_plugin)

csrf_token = generate_token(20)

username = "******"
PASSWORD = "******"


class User:
コード例 #45
0
 def test_module_shortcuts(self):
     for name in '''route get post put delete error mount
                    hook install uninstall'''.split():
         short = getattr(bottle, name)
         original = getattr(bottle.app(), name)
         self.assertWraps(short, original)
コード例 #46
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import bottle
import os
from bottle import get, run, route, template, static_file, request, response
from os import environ

application = bottle.app()


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


@application.route('/', method=['GET'])
def home():
    return template('./public/ThanhDuyen.html')


if __name__ == "__main__":
    application.run(host='0.0.0.0', port=int(environ.get('PORT', 8000)))
コード例 #47
0
        return "Restricted area <br> <a href='/logout'>Log out</a>"
    else:
        return "Aðgangur bannaður"


@route('/logout')
def logout():
    response.set_cookie('user', "", expires=0)
    return "Þú hefur verið skráður út. <br> <a href='/login'>Login</a>"


#Session lausn

session_options = {'session.type': 'file', 'session.data_dir': './data/'}

my_session = SessionMiddleware(app(), session_options)

products = [{
    'pid': 1,
    'name': 'Vara 1',
    'price': 100
}, {
    'pid': 2,
    'name': 'Vara 2',
    'price': 400
}, {
    'pid': 3,
    'name': 'Vara 3',
    'price': 200
}, {
    'pid': 4,
コード例 #48
0
 def tearDown(self):
     """Override to remove the plugins and reset the logging."""
     bottle.app().uninstall(True)
     logging.disable(logging.NOTSET)
コード例 #49
0
from  bottle import run,route,redirect,request,post,template,app,response,static_file
from sys import argv
import pymysql
from beaker.middleware import SessionMiddleware
session_opts = {
    'session.type': 'file',
    'session.data_dir': './data',
    'session.auto': True
}
app = SessionMiddleware(app(), session_opts)
products = [{"pid": 1, "name": "Billy", "price": 100.000},
            {"pid": 2, "name": "Stefán Kristinn", "price": 150.250},
            {"pid": 3, "name": "Gamli Nói", "price": 24.999},
            {"pid": 4, "name": "Jackie Chan", "price": 750.001},
            {"pid": 5, "name": "Markús Sápa", "price": 59.999},
            {"pid": 6, "name": "Marthin Luther King", "price": 749.999},
            {"pid": 7, "name": "Terry Crews", "price": 999.999},
            {"pid": 8, "name": "Siggi Sæti", "price": 20},

            ]
@route("/")
def homepage():
    return template("home.tpl")
@route('/nyskra')
def nyr():
    return template('newlogin.tpl')

@route('/donyskra', method='POST')
def nyr():
    user = request.forms.get('user')
    password = request.forms.get('pass')
コード例 #50
0
from collections import defaultdict
import webbrowser
import argparse
import logging

import bottle
from bottle import get, post, request, hook, response

from doorstop import common, build, publisher
from doorstop.common import HelpFormatter
from doorstop.server import utilities
from doorstop import settings

log = common.logger(__name__)

app = utilities.StripPathMiddleware(bottle.app())
tree = None  # set in `run`, read in the route functions
numbers = defaultdict(int)  # cache of next document numbers


def main(args=None):
    """Process command-line arguments and run the program."""
    from doorstop import SERVER, VERSION

    # Shared options
    debug = argparse.ArgumentParser(add_help=False)
    debug.add_argument('-V', '--version', action='version', version=VERSION)
    debug.add_argument('--debug', action='store_true', help=argparse.SUPPRESS)
    debug.add_argument('--launch', action='store_true', help=argparse.SUPPRESS)
    shared = {'formatter_class': HelpFormatter, 'parents': [debug]}
コード例 #51
0
ファイル: __init__.py プロジェクト: sharkevolution/tiren
from mybot import config

# Add view paths to the Bottle template path
TEMPLATE_SUB_PATHS = next(os.walk(config.BASE_TEMPLATE_PATH))[1]
TEMPLATE_PATH.append(config.BASE_TEMPLATE_PATH)

for templatePath in TEMPLATE_SUB_PATHS:
    TEMPLATE_PATH.append(os.path.join(config.BASE_TEMPLATE_PATH, templatePath))


session_opts = {
    'session.type': 'file',
    'session.cookie_expires': 30,  # Время в сек через которое закончится текущая сессия
    'session.data_dir': './data',  # Директория для хранения сесии
    'session.auto': True
}

# app = Bottle()
app = SessionMiddleware(bottle.app(), session_opts)

from .controllers import *

# if config.DEBUG:
#     print("ROOT_PATH: %s" % config.ROOT_PATH)
#     print("Template Paths:")
#
#     for it in bottle.TEMPLATE_PATH:
#         print("   %s" % it)

コード例 #52
0
def homepage():
    """Render the home page."""
    return {'sample': 'graphrest'}

@bottle.route('/login')
def login():
    """Prompt user to authenticate."""
    MSGRAPH.login('/graphcall')

@bottle.route('/login/authorized')
def authorized():
    """Handler for the application's Redirect Uri."""
    MSGRAPH.redirect_uri_handler()

@bottle.route('/graphcall')
@bottle.view('graphcall.html')
def graphcall():
    """Confirm user authentication by calling Graph and displaying some data."""
    endpoint = MSGRAPH.api_endpoint('me')
    graphdata = MSGRAPH.get(endpoint).json()
    return {'graphdata': graphdata, 'endpoint': endpoint, 'sample': 'graphrest'}

@bottle.route('/static/<filepath:path>')
def server_static(filepath):
    """Handler for static files, used with the development server."""
    root_folder = os.path.abspath(os.path.dirname(__file__))
    return bottle.static_file(filepath, root=os.path.join(root_folder, 'static'))

if __name__ == '__main__':
    bottle.run(app=bottle.app(), server='wsgiref', host='localhost', port=5000)
コード例 #53
0
ファイル: application.py プロジェクト: 3thirty/strava_charts
from bottle import route, run, template, request, response, redirect, \
                   static_file
from bottle.ext import beaker

from Activity import ActivityList, AggregationPeriod
from Chart import Chart
from Strava import Strava, Authentication, AuthenticationException, \
                   CookieTokenStorage

session_opts = {
    'session.type': 'memory',
    'session.cookie_expires': 300,
    'session.auto': True
}

application = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)


@route('/favico/<file:re:.*\\.(ico|png|webmanifest)$>')
@route('/<file:re:favicon.ico$>')
def favico(file):
    return static_file(file, root="favico/")


@route('/ping')
def ping():
    return 'pong'


@route('/dump')
def main():
コード例 #54
0
from gevent import monkey
monkey.patch_all()

import bottle

# def do_compute():

#     i = 0
#     for _ in range(90000):
#         i += 1


@bottle.get('/')
def home_page():

    # do_compute()
    return 'Hello World'


if '__main__' == __name__:

    ws_port = 8082
    debug = False
    host = '0.0.0.0'
    bottle.run(app=bottle.app(),
               host=host,
               port=ws_port,
               debug=debug,
               server="gevent")
コード例 #55
0
#! /usr/bin/env python2

from bottle import route, run, template, request, app, redirect, static_file
from beaker.middleware import SessionMiddleware
import sys

session_opts = {
    'session.type': 'file',
    'session.cookie_expires': 300000,
    'session.data_dir': '/tmp/session',
    'session.auto': True,
    'session.key': "sessionid"
}

app = application = myapp = SessionMiddleware(app(), session_opts)


@route('/')
def root_page():
    session = request.environ.get('beaker.session')
    if ('log_in' in session and session['log_in'] == True):
        return template("welcome.html", name=session['login'])
    else:
        session['log_in'] = False
        redirect("/login")


@route('/login')
def authentication():
    username = request.params.get('username')
    password = request.params.get('password')
コード例 #56
0
ファイル: server.py プロジェクト: katyukha/file-server
    parser.add_argument("--port",
                        default='8000',
                        type=int,
                        dest='port',
                        help='Port to listen to'),
    parser.add_argument("--server",
                        default='wsgiref',
                        dest='server',
                        help='Server adapter to use'),
    parser.add_argument("--debug",
                        action='store_true',
                        help='Enable dubug mode'),
    parser.add_argument("--reload",
                        action="store_true",
                        help="auto-reload on file changes."),
    args = parser.parse_args()

    debug(args.debug)
    run(host=args.host,
        port=args.port,
        server=args.server,
        reloader=args.reload)
else:
    # Change working directory so relative paths (and template lookup) work again
    import os
    import os.path
    os.chdir(os.path.dirname(__file__))

    from bottle import app
    application = app()
コード例 #57
0
        except Exception as e:
            return bottle.redirect('/routes?{0}'.format(urlencode({'msg': str(e)})))

    return {"title": "DockerAnon | Routes",
            "proxy": list(Data.get('proxies').keys()),
            "msg": bottle.request.query.msg}


@bottle.route("/dns/add", method=('POST', 'GET'))
@bottle.view('views/dns_add.html')
def routes_add():
    if bottle.request.forms.get('name') is not None:
        dns_entry = {}
        dns_entry['name'] = bottle.request.forms.get('name')
        dns_entry['type'] = bottle.request.forms.get('dtype')
        dns_entry['value'] = bottle.request.forms.get('value')
        if dns_entry['value'] is None or dns_entry['value'] == '':
            return bottle.redirect('/dns/add?{0}'.format(urlencode({'msg': 'Value field is mandatory'})))
        new_dns = Data.get('dns')[:]
        new_dns.append(dns_entry)
        Data.set('dns', new_dns)
        Data.save()
        DNS.ask_for_reload()
        return bottle.redirect('/dns')

    return {"title": "DockerAnon | DNS",
            "msg": bottle.request.query.msg}


bottle.run(bottle.app(), host='0.0.0.0', port=80, debug=False, reloader=False)
コード例 #58
0
 def setUp(self):
     self.app = webtest.TestApp(bottle.app())
コード例 #59
0
ファイル: app.py プロジェクト: rjmax/scratch
"""
This script runs the application using a development server.
"""

import bottle
import os
import sys
from bottle import route, run, response, request
import json
import opsCenter
import nodes

bottle.app().catchall = False


@route('/')
def hello():
    response.headers['Content-Type'] = 'application/json'

    # This python script generates an ARM template that deploys DSE across multiple datacenters.
    with open('clusterParameters.json') as inputFile:
        clusterParameters = json.load(inputFile)

    locations = request.query['locations'].split(",")
    vmSize = request.query['vmSize']
    nodeCount = int(request.query['nodeCount'])
    adminUsername = request.query['adminUsername']
    adminPassword = request.query['adminPassword']

    # This is the skeleton of the template that we're going to add resources to
    generatedTemplate = {
コード例 #60
0
 def test_missing_session(self):
     """Test that the session is invalid when it's missing."""
     self.mock_database.sessions.find_one.return_value = None
     route = bottle.Route(bottle.app(), "/", "POST", self.route)
     self.assertRaises(bottle.HTTPError, route.call)