Example #1
0
 def start_ide():
     # Development server
     debug(True)
     print "======================================================="
     print "Django IDE Launched on http://localhost:8080/django-ide"
     print "======================================================="
     run(host="localhost", port=8080)
Example #2
0
def app(root=None,
        redirect_to_fallback=True,
        fallback_url=None,
        password_file=None):
    import sys, os
    from pypiserver import core
    sys.modules.pop("pypiserver._app", None)
    __import__("pypiserver._app")
    _app = sys.modules["pypiserver._app"]

    import bottle

    if root is None:
        root = os.path.expanduser("~/packages")

    if fallback_url is None:
        fallback_url="http://pypi.python.org/simple"

    #os.listdir(root)
    _app.configure(root=root, redirect_to_fallback=redirect_to_fallback, fallback_url=fallback_url,
                   password_file=password_file)
    _app.app.module = _app

    bottle.debug(True)
    return _app.app
def main():
    """
    If run as a script, parse command line arguments and start embedded server
    """

    parser = ArgumentParser(description="Serves up the useful-cookery.com website")
    parser.add_argument("-d", "--debug", type=int, default=0, help="set debug level to DEBUG (default: %(default)s)")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-q", "--quiet", action="store_true")
    group.add_argument("-v", "--verbose", action="store_true")

    opts = parser.parse_args()

    global DEBUG
    DEBUG = opts.debug

    if DEBUG >= 3:
        print('opts="%s"' % opts, file=sys.stderr)

    if DEBUG > 0:
        bottle.debug(True)

    recipes.setDebug(DEBUG)

    bottle.run(reloader=(DEBUG > 0))
Example #4
0
def main():
    """
    Main loop
    """

    # Initialiseer argparse
    parser = argparse.ArgumentParser(description='DVS HTTP interface test tool')

    parser.add_argument('-c', '--config', dest='configFile',
        default='config/http.yaml', action='store',
        help='HTTP configuratiebestand')

    # Parse config:
    args = parser.parse_args()
    config = dvs_util.load_config(args.configFile)

    # Stel logger in:
    dvs_util.setup_logging(config)

    dvs_http_interface.config = config

    # Start bottle:
    logger = logging.getLogger(__name__)
    logger.info("DVS server: %s", config['dvs']['daemon'])

    bottle.debug(True)
    bottle.run(host='localhost', port=8080, reloader=True)
Example #5
0
def param_update(db): 
    params = db.query(models.SlcParam)
    for param in params:
        if param.param_name in request.forms:
            _value = request.forms.get(param.param_name)
            if _value: 
                param.param_value = _value  
                
    ops_log = models.SlcRadOperateLog()
    ops_log.operator_name = get_cookie("username")
    ops_log.operate_ip = get_cookie("login_ip")
    ops_log.operate_time = utils.get_currtime()
    ops_log.operate_desc = u'操作员(%s)修改参数'%(get_cookie("username"))
    db.add(ops_log)
    db.commit()
    
    websock.reconnect(
        request.forms.get('radiusd_address'),
        request.forms.get('radiusd_admin_port'),
    )
        
    is_debug = request.forms.get('is_debug')
    bottle.debug(is_debug == '1')
    
    websock.update_cache("is_debug",is_debug=is_debug)
    websock.update_cache("reject_delay",reject_delay=request.forms.get('reject_delay'))
    websock.update_cache("param")
    redirect("/param")
def main():
    global runtime_info, log_directory, verbose

    parser = argparse.ArgumentParser(
        description="web viewer for runtime statistics")
    parser.add_argument(
        "log_directory", help="directory containing logs for all experiments")
    parser.add_argument(
        "--port", "-p", help="port on which the web viewer runs", default=9090,
        type=int)
    parser.add_argument(
        "-v", "--verbose", default=False, action="store_true",
        help="Print detailed log processing information")

    args = parser.parse_args()
    log_directory = args.log_directory
    verbose = args.verbose

    if (not os.path.exists(log_directory) or
        not os.path.isdir(log_directory)):

        parser.error("'%s' doesn't exist or is not a directory" %
                     (log_directory))

    bottle.debug(True)
    return bottle.run(host='0.0.0.0', port=args.port)
Example #7
0
def SetUpApp( custom_options = {} ):
  bottle.debug( True )
  options = user_options_store.DefaultOptions()
  options.update( custom_options )
  handlers.UpdateUserOptions( options )
  extra_conf_store.Reset()
  return TestApp( handlers.app )
    def setUp(self):
        bottle.debug() # force debug messages in error pages returned by webtest

        self.app = TestApp(main.application)
        self.db = COMP249Db()
        self.db.create_tables()
        self.db.sample_data()
Example #9
0
def get_app(debug=None, settings_file='',
            compressed_static=None, settings=settings):
    """
        Return a tuple (settings, app) configured using passed
        parameters and/or a setting file.
    """
    if settings_file:
        settings.update_with_file(os.path.abspath(settings_file))

    if settings.PASTE_ID_LENGTH < 4:
        raise SettingsValidationError('PASTE_ID_LENGTH cannot be lower than 4')

    if compressed_static is not None:
        settings.COMPRESSED_STATIC_FILES = compressed_static

    if debug is not None:
        settings.DEBUG = debug

    # make sure the templates can be loaded
    for d in reversed(settings.TEMPLATE_DIRS):
        bottle.TEMPLATE_PATH.insert(0, d)

    if settings.DEBUG:
        bottle.debug(True)

    return settings, app
Example #10
0
 def test_unexpected_error_debug(self):
     bottle.debug(True)
     resp = self.app.get('/unexpected_error', expect_errors=True)
     bottle.debug(False)
     self.assertEqual(resp.status_code, 500)
     self.assertIn('reason', resp.json_body)
     self.assertIn('code', resp.json_body)
     self.assertIn('message', resp.json_body)
     self.assertIn('exception', resp.json_body)
     self.assertIn('traceback', resp.json_body)
     self.assertEqual(
         len(resp.json_body['traceback'].splitlines()),
         14
     )
     self.assertEqual(
         resp.json_body['exception'],
         "Exception('My logic is bad.',)"
     )
     self.assertEqual(
         resp.json_body['message'],
         "We're sorry, something went wrong."
     )
     self.assertEqual(
         resp.json_body['reason'],
         "Internal Server Error"
     )
     self.assertEqual(
         resp.json_body['code'],
         500
     )
Example #11
0
 def test_worst_middleware(self):
     bottle.debug(True)
     resp = self.app.get('/', expect_errors=True)
     bottle.debug(False)
     self.assertEqual(resp.status_code, 500)
     self.assertIn('reason', resp.json_body)
     self.assertIn('code', resp.json_body)
     self.assertIn('message', resp.json_body)
     self.assertIn('exception', resp.json_body)
     self.assertIn('traceback', resp.json_body)
     self.assertEqual(
         len(resp.json_body['traceback'].splitlines()),
         6
     )
     self.assertEqual(
         resp.json_body['exception'],
         "Exception('Bugs!',)"
     )
     self.assertEqual(
         resp.json_body['message'],
         "We're sorry, something went wrong."
     )
     self.assertEqual(
         resp.json_body['reason'],
         "Internal Server Error"
     )
     self.assertEqual(
         resp.json_body['code'],
         500
     )
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)
Example #13
0
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)
Example #14
0
 def test_keyboard_debug(self):
     bottle.debug(True)
     resp = self.app.get('/keyboard', expect_errors=True)
     bottle.debug(False)
     self.assertEqual(resp.status_code, 500)
     self.assertIn('reason', resp.json_body)
     self.assertIn('code', resp.json_body)
     self.assertIn('message', resp.json_body)
     self.assertIn('exception', resp.json_body)
     self.assertIn('traceback', resp.json_body)
     self.assertEqual(
         len(resp.json_body['traceback'].splitlines()),
         14
     )
     self.assertEqual(
         resp.json_body['exception'],
         "KeyboardInterrupt('A funny signal.',)"
     )
     self.assertEqual(
         resp.json_body['message'],
         "We're sorry, something went wrong."
     )
     self.assertEqual(
         resp.json_body['reason'],
         "Internal Server Error"
     )
     self.assertEqual(
         resp.json_body['code'],
         500
     )
Example #15
0
def main():
    global DB_SERVER, DB_ADDRESS

    print 'Using YouFace server at', DB_ADDRESS
    DB_SERVER = xmlrpclib.ServerProxy(DB_ADDRESS, allow_none=True)
    debug(True)
    run(host='localhost', port=8080, reloader=True)
Example #16
0
def main():
    opts = parser.parse_args()
    
    if opts.verbose:
        bottle.debug(True)
    with GameServer(singleConnect = opts.single) as app:
        bottle.run(app, host = opts.server, port = opts.port, reloader=True, server = bottle.CherryPyServer)
Example #17
0
def run_webapp():

    @route('/', method='GET')
    @view('search_template')
    def search_page():
        """Main search page."""
        query = request.GET.get('query', '').strip()
        # Convert query to unicode.
        query = query.decode('utf-8')
        log.info('Web query: ' + query)
        answers = []
        if query:
            banana = Banana()
            answers = banana.search(query)
        return dict(answers=answers)

    @route('/static/<filepath:path>')
    def server_static(filepath):
        """Serve static files (css for instance)."""
        log.info(filepath)
        return static_file(filepath, root='./static')

    log = logging.getLogger(__name__)
    debug(True)
    run(host='localhost', port=8000, reloader=True)
Example #18
0
def main():
    bottle.debug(True)
    bottle.run(host='0.0.0.0', port=8090)

    client = MongoClient()
    db = client.test
    #
    #   filler data
    #
    addToDB(db, "Steve Rogers", "avengers.com/cap", ["shield throwing", "Java"], "20055")
    addToDB(db, "Natasha Romanov", "avengers.com/widow", ["assassination", "snark", "CSS"], "20055")
    addToDB(db, "Sam Wilson", "avengers.com/falcon", ["bird suit", "Java", "HTML", "CSS"], "20055")
    #
    #   /filler data
    #
    skills = searched()
    zipcode = "20055"
    skillMatchThreshold = 0.5
    matchedWorkers = searchDB(db, skills, zipcode, skillMatchThreshold)
    if (len(matchedWorkers) < 10):
        # new scrape
        # add to DB
        pass

    searched(matchedWorkers)
    client.drop_database(db)
Example #19
0
def main(argv, tpl = './tpl.html', cfg = './cfg.json', debug = False, port = 8080):
    """ Parses the command line arguments and starts the server. """
    
    try:
        opts, args = getopt.getopt(argv, 'ht:c:p:d', ['help', 'tpl=', 'cfg=', 'port='])                               
    except getopt.GetoptError:
        usage()          
        sys.exit(2)                     
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit()                  
        elif opt == '-d':                
            debug = True              
        elif opt in ('-t', '--tpl'): 
            tpl = arg
        elif opt in ('-c', '--cfg'): 
            cfg = arg
        elif opt in ('-p', '--port'):
            port = arg
    
    global engine
    engine = Engine(tpl, cfg)
    bottle.debug(debug)
    bottle.run(host='localhost', port=port)
Example #20
0
def setup_logging(args, conf):
    """Setup logging
    """
    logfile = args.logfile or conf.logfile

    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s [%(process)d] %(levelname)s %(name)s (%(funcName)s) %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'  # %z for timezone
    )
    log.addHandler(web_log_handler)
    if args.debug:
        log.debug("Debug mode")
        log.debug("Configuration file: %r", args.cf)
        log.debug("Logfile (unused in debug mode): %r", logfile)
        bottle.debug(True)

    else:
        logging.basicConfig(
            level=logging.DEBUG,
        )
        fh = logging.handlers.TimedRotatingFileHandler(
            logfile,
            when='midnight',
            utc=True,
        )
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(
            logging.Formatter(
                '%(asctime)s [%(process)d] %(levelname)s %(name)s %(module)s:%(funcName)s:%(lineno)s %(message)s'))
        log.addHandler(fh)
Example #21
0
def serve(args):
    import bottle
    from engineer.conf import settings
    from engineer import emma

    logger = logging.getLogger(__name__)

    if not settings.OUTPUT_DIR.exists():
        logger.warning(
            "Output directory doesn't exist - did you forget to run 'engineer build'?")
        exit()

    debug_server = bottle.Bottle()
    debug_server.mount('/_emma', emma.Emma().app)

    @debug_server.route('/')
    @debug_server.route('/<filepath:path>')
    def serve_static(filepath='index.html'):
        if settings.HOME_URL != '/':
            # if HOME_URL is not root, we need to adjust the paths
            if filepath.startswith(settings.HOME_URL[1:]):
                filepath = filepath[len(settings.HOME_URL) - 1:]
            else:
                return bottle.HTTPResponse(status=404)
        response = bottle.static_file(filepath, root=settings.OUTPUT_DIR)
        if type(response) is bottle.HTTPError:
            return bottle.static_file(path(filepath) / 'index.html',
                                      root=settings.OUTPUT_DIR)
        else:
            return response

    bottle.debug(True)
    bottle.run(app=debug_server, host='0.0.0.0', port=args.port, reloader=True)
def main():
    print "======================================================="
    print " RN1723 Secure Test Server Application Version: %s   \r\n" % APP_VERSION
    print "======================================================="

    bottle.debug(True)
    bottle.run(app=app, host=HOST_IP_ADDRESS, port=PORT, server='mysslcherrypy', quiet=False, reloader=True)
Example #23
0
def navi_loop(p, address, port):
    # Look, bottle makes me do sad things..
    global proc
    proc = p

    bottle.debug(True)
    bottle.run(host=address, port=port, reloader=False, quiet=True)
Example #24
0
def run(addr='localhost', port=9090, **kwargs):
    bottle.debug(kwargs.pop('debug', False))
    bottle.run(app=app, host=addr, port=port,
               **dict({'reloader': kwargs.pop('reload', False), 
                       'interval': kwargs.pop('reload_interval', 1),
                       'server' : ZMQServer},
                      **kwargs))
Example #25
0
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'])
def main():
    parser = ArgumentParser(description="Run Graph Explorer")
    parser.add_argument("configfile", metavar="CONFIG_FILENAME", type=str)
    parser.add_argument("--debug", type=bool)
    args = parser.parse_args()

    config.init(args.configfile)
    
    c = ConfigValidator(obj=config)
    if not c.validate():
        print "Configuration errors (%s):" % args.configfile
        for (key, err) in c.errors.items():
            print key,
            for e in err:
                print "\n    %s" % e
        sys.exit(1)

    app_dir = os.path.dirname(__file__)
    if app_dir:
        os.chdir(app_dir)

    debug(args.debug)
    run('graph_explorer.app',
        reloader=True,
        host=config.listen_host,
        port=config.listen_port,
        server=PasteServer)
Example #27
0
def deploy_service(postgres, host, port):
    """jhj
    """
    try:
        conn_info = pg_connection(conn_str=postgres)
    except ConnectionError as e:
        click.echo('Postgres connection error: {}'.format(e.args))
        return

    db = PGPlugin('db', **conn_info)

    version = db.version

    click.echo('\nChecking connectivity: ....\n')
    click.echo('Postgres Info: {}'.format(version))

    click.echo('dbapi-viewer server at: http://{}:{}'.format(host, port))

    dbviewer_service.install(db)

    bottle.debug(True)
    bottle.run(
        app=dbviewer_service,
        server='cherrypy',
        port=port,
        host=host,
        reloader=True
    )
Example #28
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 #29
0
    def __init__(self, app, hostname='localhost', port=9000,
                 pidfile='/var/run/decanter.pid', development=False):
        self.app = app
        self.hostname = hostname
        self.port = int(port)
        self.pidfile = pidfile
        self.config = Config()

        if 'timezone' in self.config:
            os.environ['TZ'] = self.config.timezone

        if 'memfile_max' in self.config:
            bottle.Request.MEMFILE_MAX = self.config.memfile_max

        # remove all default bottle plugins
        bottle.uninstall(True)
        bottle.debug(self.config.debug)

        # install plugins
        self.install(plugins=self.config.plugins)
        if self.config.debug or not development:
            stdout = os.popen('tty').read().strip()
            stderr = os.popen('tty').read().strip()

        if not development:
            super(Decanter, self).__init__(
                pidfile, stdout=stdout, stderr=stderr)
Example #30
0
def set_skid():
    """
        direktes Anfahren einer neuen Schlittenposition
    """
    debug('setzte neue Schlittenposition: ' + str(request.POST['newPos']), 0)
    q.put((3, int(request.POST['newPos'])))
    return 'skid pos set'
import unittest
import bottle
import webtest
import main

bottle.debug()


class FunctionalTests(unittest.TestCase):
    def setUp(self):
        self.app = webtest.TestApp(main.app)
        main.SESSIONS = {}

    def test_get_positions(self):
        """the URL /positions returns a JSON list of
        positions"""

        result = self.app.get('/positions')

        self.assertEqual(result.status, "200 OK")
        self.assertEqual(result.content_type, 'application/json')
        self.assertEqual(len(result.json), 168)

    def test_cookie_set(self):
        """When I request the main page, I get a new session cookie
        """

        result = self.app.get('/')
        self.assertIn(main.COOKIE_NAME, self.app.cookies)
        sessionid = self.app.cookies[main.COOKIE_NAME]
Example #32
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from ..server_utils import SetUpPythonPath
SetUpPythonPath()
from webtest import TestApp
from .. import handlers
from nose.tools import ok_, eq_, with_setup
from .test_utils import Setup
import bottle

bottle.debug(True)


@with_setup(Setup)
def SemanticCompletionAvailable_Works_test():
    app = TestApp(handlers.app)
    request_data = {'filetypes': ['python']}

    ok_(app.post_json('/semantic_completion_available', request_data).json)


@with_setup(Setup)
def UserOptions_Works_test():
    app = TestApp(handlers.app)
    options = app.get('/user_options').json
    ok_(len(options))
Example #33
0
def start(logfile=None, profile=False):
    """ Start the application """

    config = app.config

    log_config({
        'version': 1,
        'root': {
            'handlers': ['file'],
            'level': logging.DEBUG,
        },
        'handlers': {
            'file': {
                'class': 'logging.handlers.RotatingFileHandler',
                'formatter': 'default',
                'filename': logfile or config['logging.output'],
                'maxBytes': int(config['logging.size']),
                'backupCount': int(config['logging.backups'])
            },
        },
        'formatters': {
            'default': {
                'format': config['logging.format'],
                'datefmt': config['logging.date_format']
            },
        },
    })

    # Make sure all necessary directories are present
    ensure_dir(dirname(config['logging.output']))
    ensure_dir(dirname(config['database.path']))
    ensure_dir(config['content.spooldir'])
    ensure_dir(config['content.appdir'])
    ensure_dir(config['content.contentdir'])
    ensure_dir(config['content.covers'])

    # Run database migrations
    db = squery.Database(config['database.path'])
    migrations.migrate(db, in_pkg('migrations'))
    logging.debug("Finished running migrations")
    db.disconnect()

    app.install(squery.database_plugin)

    # Set some basic configuration
    bottle.TEMPLATE_PATH.insert(0, in_pkg('views'))
    bottle.BaseTemplate.defaults.update({
        'app_version':
        __version__,
        'request':
        request,
        # Translators, used as default page title
        'title':
        _('Librarian'),
        'style':
        'screen',  # Default stylesheet
        'h':
        helpers,
        'updates':
        Lazy(lambda: len(list(get_zipballs()))),
        'readable_license':
        lambda s: dict(LICENSES).get(s, LICENSES[0][1]),
        'is_rtl':
        Lazy(lambda: request.locale in RTL_LANGS),
        'u':
        to_unicode,
    })

    # Add middlewares
    wsgiapp = app  # Pass this variable to WSGI middlewares instead of ``app``
    wsgiapp = I18NPlugin(wsgiapp,
                         langs=LOCALES,
                         default_locale=DEFAULT_LOCALE,
                         domain='librarian',
                         locale_dir=in_pkg('locales'))

    # Srart the server
    logging.info('Starting Librarian')

    if profile:
        # Instrument the app to perform profiling
        print('Profiling enabled')
        from repoze.profile import ProfileMiddleware
        wsgiapp = ProfileMiddleware(
            wsgiapp,
            log_filename=config['profiling.logfile'],
            cachegrind_filename=config['profiling.outfile'],
            discard_first_request=True,
            flush_at_shutdown=True,
            path='/__profile__',
            unwind=False,
        )

    bottle.debug(config['librarian.debug'] == 'yes')
    bottle.run(app=wsgiapp,
               server=config['librarian.server'],
               host=config['librarian.bind'],
               reloader=config['librarian.server'] == 'wsgiref',
               port=int(config['librarian.port']))
Example #34
0
@route('/status/update', method='POST')
def update_status():
    ''' update task status '''
    # decode json message body into Python dictionary
    task_data = unpack_task(request) 

    # you may remove or comment out the print statements
    print("from update_status: ")
    print(task_data)

    updated_task = view_update_status(task_data)

    print(updated_task)

    return pack_task(updated_task)

@route('/static/<filename>')
def static(filename):
    if filename:
        return static_file(filename, root='./static')
    else:
        return '<script>alert("File name is missing")</script>' 

# during development (not in production)
debug(True)

# start bottle webserver on localhost:8080
# reload script after change (without restarting server)
run(reloader=True)
Example #35
0
        '-H',
        '--host',
        dest='host',
        default='localhost',
        help='host/IP to run the server on (default: localhost)')
    parser.add_argument(
        '-p',
        '--port',
        dest='port',
        type=int,
        default=8000,
        help='port number to run the server on (default: 8000)')
    parser.add_argument('-d',
                        '--debug',
                        dest="debug",
                        default=False,
                        action="store_true",
                        help='set debug mode')
    parser.add_argument('-t',
                        '--timeout',
                        dest='timeout',
                        type=int,
                        default=120,
                        help='timeout before deleting stale pretenders')

    args = parser.parse_args()
    bottle.debug(args.debug)
    settings.TIMEOUT_PRETENDER = args.timeout
    LOGGER.debug('Setting pretender timeout: {0}'.format(args.timeout))
    run(args.host, args.port)
Example #36
0
import requests
from models import *
from common import *
from datetime import datetime, timedelta

from tornado.template import Template
from sqlalchemy import literal, select, func, case, union_all, and_, null, or_

engine = create_engine(
    'postgresql+psycopg2://%s:%s@%s/%s' %
    (settings.USER, settings.PASSWORD, settings.DATA_HOST, settings.DATABASE),
    echo=True,
    client_encoding='utf8')
Session = sessionmaker(bind=engine)

bottle.debug(settings.DEBUG)
app.catchall = False
bottle.TEMPLATE_PATH.append(settings.TEMPLATE_PATH)


def token_auth(func):
    def wrapper(*args, **kwargs):
        try:
            token = request.headers.get("Token")
            if not token:
                raise Exception(u"必须传递令牌")
            data = jwt.decode(token, settings.secret)
            kwargs["access_level"] = data.get("access_level")
            kwargs["token"] = data.get("token")
            kwargs["set_of_book"] = data.get("set_of_book")
            kwargs["url"] = data.get("url")
Example #37
0
parser = ConfigParser.ConfigParser(
    dict(remote_ip='192.168.1.254',
         remote_port='1024',
         debug='0',
         server_port='8080',
         callsign='0'))

parser.read(
    ["settings.ini",
     os.path.join(os.path.dirname(__file__), 'settings.ini')])

if not parser.has_section("Server"):
    parser.add_section("Server")

bottle.debug(parser.getboolean('Server', 'debug'))

CALL_FILE = os.path.join(os.path.dirname(__file__), 'call.wav')

REMOTE = (parser.get('Server',
                     'remote_ip'), parser.getint('Server', 'remote_port'))

MAPPING = {
    'up': 'M_UP',
    'down': 'M_DOWN',
    'left': 'M_LEFT',
    'right': 'M_RIGHT',
    'cam1': 'N_1',
    'cam2': 'N_2',
    'cam3': 'N_3',
    'cam4': 'N_4',
def set_config():
    try:
        data_obj = json.loads(request.body.readlines()[0])
        if not isinstance(data_obj, dict):
            raise ValueError
        if not data_obj.viewkeys():
            raise ValueError
    except (ValueError, IndexError):
        response.status = 400
        return json_error("Wrong POST data format", 400)

    for key, val in data_obj.items():
        # TODO: allow only defined variable names with defined value type and
        # maximum length
        rdb.hset(ns.config, key, val)
    return resp_or_404(json.dumps(data_obj))


# Serve static content to eliminate the need of apache in development env.
# For this to work additional routes for /backend/* paths were added because
# they are used in the frontend.
@route('/')
@route('/<filename:path>')
def static(filename="index.htm"):
    return static_file(filename, "../frontend/static/")


if __name__ == '__main__':
    debug(mode=True)
    run(host='localhost', port=8080, reloader=True)
Example #39
0
def set_bottle_debug_mode(request):
    """Ensures that bottle is set to use debug mode."""
    bottle.debug(True)
Example #40
0
def spy(module_name, filepath):
    # print("spy", module_name, filepath)
    try:
        code_file = DS.get_file_contents("_spy", module_name, filepath)
        code_str = dcd(str.encode(code_file.content)).decode("utf-8")
    except UnknownObjectException as _:
        # code_str = "# File not found"
        raise HTTPError(404)

    return code_str


# Static Routes
@get(
    "/<:path>/<project_name>/__code/<module_name:re:[a-z].*>/<filepath:re:.*\.py>"
)
def local_spy(project_name, module_name, filepath):
    print("local_spyspy", project_name, module_name, filepath)
    try:
        code_file = DS.get_file_contents(project_name, module_name, filepath)
        code_str = dcd(str.encode(code_file.content)).decode("utf-8")
    except UnknownObjectException as _:
        # code_str = "# File not found"
        raise HTTPError(404)
    return code_str


appbottle = Bottle(
)  # create another WSGI application for this controller and resource.
debug(True)  #  uncomment for verbose error logging. Do not use in production
Example #41
0
# -*- coding:utf-8 mode:Python -*-
from bottle import route, run, template, static_file, debug
debug(True)  #for debug


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


@route('/css/<name>')
def get_css(name):
    return static_file(filename=name, root='./static/css')


@route('/fonts/<name>')
def get_fonts(name):
    return static_file(filename=name, root='./static/fonts')


@route('/js/<name>')
def get_js(name):
    return static_file(filename=name, root='./static/js')


@route('/<name>')
def root_file(name):
    return static_file(filename=name, root='./static')


@route('/hello/<name>')
Example #42
0
def main():
    import bottle
    bottle.debug(True)
    vlevel = 2 if 'verbose' in sys.argv else 0
    result = unittest.TextTestRunner(verbosity=vlevel).run(suite)
    sys.exit((result.errors or result.failures) and 1 or 0)
Example #43
0
def run():
    bottle.debug(not PROD)
    bottle.run(app=app, host='localhost', port='2081', reloader=not PROD)
Example #44
0
def run_app():
    args = start()
    debug(args.debug)
    run(host=args.host, port=args.port, reloader=args.debug)
Example #45
0
            'short_code': custom_short_code
        },
                          indent=4)
    else:
        redis.set(custom_short_code, long_url)
    return json.dumps({
        'success': 'true',
        'short_code': custom_short_code
    },
                      indent=4)


# redirect /{custom_short_code} endpoint to a long url
@route('/<custom_short_code>')
def redirect(custom_short_code):
    long_url = redis.get(custom_short_code)
    if long_url is not None:
        bottle.redirect(long_url, 301)
    else:
        return json.dumps({
            'success': 'false',
            'short_code': custom_short_code
        },
                          indent=4)


if __name__ == '__main__':
    # To run the server, type-in $ python server.py
    bottle.debug(True)  # display traceback
    run(host='localhost', port=8080, reloader=True)
Example #46
0
import search
from data import cleaner

dc = cleaner.DataCleaner()
zs = search.ZapSearch(esUrl=argv[2], cleaner=dc)


# serves the homepage
@get('/')
def index():
    return template('zapapp/views/main.tpl')


# essentially a proxy to ES
@get('/search')
def search():
    response.content_type = 'application/json'
    return json.dumps(zs.search(request.query.query))


# static files
@route('/static/:path#.+#', name='static')
def static(path):
    return static_file(path, root='zapapp/static')


if __name__ == "__main__":
    bottle.debug(True)  # TODO(jeffk)
    bottle.run(host='0.0.0.0', port=argv[1])
Example #47
0
from module.common.JsEngine import JsEngine

JS = JsEngine()

TEMPLATE = smart_text(config.get('webinterface', 'template'))
DL_ROOT = smart_text(config.get('general', 'download_folder'))
LOG_ROOT = smart_text(config.get('log', 'log_folder'))
PREFIX = smart_text(config.get('webinterface', 'prefix'))

if PREFIX:
    PREFIX = PREFIX.rstrip("/")
    if not PREFIX.startswith("/"):
        PREFIX = "/" + PREFIX

DEBUG = config.get("general", "debug_mode") or "-d" in sys.argv or "--debug" in sys.argv
bottle.debug(DEBUG)

cache = join("tmp", "jinja_cache")
if not exists(cache):
    makedirs(cache)

bcc = FileSystemBytecodeCache(cache, '%s.cache')

mapping = {'js': FileSystemLoader(join(PROJECT_DIR, 'media', 'js'))}
for template in os.listdir(join(PROJECT_DIR, "templates")):
    if os.path.isdir(join(PROJECT_DIR, "templates", template)):
        mapping[template] = FileSystemLoader(join(PROJECT_DIR, "templates", template))

loader = PrefixLoader(mapping)

env = Environment(loader=loader, extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape'], trim_blocks=True, auto_reload=False,
Example #48
0
        bottle.response.set_cookie("session", "")
        bottle.redirect('/login')


def get_session():
    """
    Retrieves session from browser's stored cookie, if the session is valid
    """
    cookie = bottle.request.get_cookie("session")
    if not cookie:
        print "Sorry, no cookie in the cookie jar"
        return None
    else:
        session_id = manage_users.get_session_from_cookie(cookie)
        if not session_id:
            print "Sorry, your cookie didn't generate properly"
            return None
        else:
            session = manage_users.get_session_from_db(session_id)
    return session


if __name__ == '__main__':
    if os.environ.get('ENVIRONMENT') == 'PRODUCTION':
        PORT = int(os.environ.get('PORT', 5000))
        print "port = %d" % PORT
        bottle.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))
    else:
        bottle.debug(True)  #dev only, not for production
        bottle.run(host='localhost', port=8082, reloader=True)  #dev only
Example #49
0
def wsgi():
    bottle.debug(DEBUG)
    return bottle.app()
Example #50
0
def main():
    # Start the Bottle webapp
    bottle.debug(True)
    bottle.run(host='0.0.0.0', port=80, app=app, quiet=False, reloader=True)
Example #51
0
    def _init_logging(self):
        # bottle debug
        debug(True)

        init_logging()
Example #52
0
#!/usr/bin/env python
import bottle
import webtools
import MySQLdb as db
import random
import re

CFG = webtools.ServerConfig()

bottle.debug(CFG.IS_DEV)

route = bottle.route
template = bottle.template
request = bottle.request
response = bottle.response


@route('/')
def index():
    return template('index')


@route('/about')
def about():
    return template('about')


@route('/contact')
def contact():
    return template('contact')
Example #53
0
import bottle
from bottle import jinja2_template as template
from bottle import response, run, static_file
# Import Bottle Extensions
from bottle_sqlalchemy import SQLAlchemyPlugin
# Import SQLAlchemy
from sqlalchemy import Column, Integer, String, Text, create_engine
from sqlalchemy.ext.declarative import declarative_base

# Define dirs
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, 'static')

# App Config
bottle.TEMPLATE_PATH.insert(0, os.path.join(BASE_DIR, 'templates'))
bottle.debug(True)  # Don't forget switch this to `False` on production!

# SQLite Database config
Base = declarative_base()
db_engine = create_engine('sqlite:///' + os.path.join(BASE_DIR, 'articles.db'))

# Starting App
app = bottle.default_app()

# Install Bottle plugins
app.install(SQLAlchemyPlugin(db_engine, keyword='sqlite_db'))


# Articles Database class
class ArticlesDB(Base):
    __tablename__ = 'articles'
Example #54
0
	print ""

	print "System paths:"
	for it in paths:
		print "   %s" % it

	print "\n%s\n" % datetime.today()


#
# Setup our pre-request plugin, session, debug mode, and methods
# to serve static resources.
#
install(bottle_preRequest.preRequest)
bottle.debug(config.DEBUG)

@route("/resources/<filepath:path>")
def serve_static(filepath):
	return static_file(filepath, root = config.RESOURCES_PATH)

@route("/heartbeat", method = "GET")
def heartbeat():
	return "A-OK ya'll!"

#
# Uncomment line 84 and comment line 83 to enable session management
#
app = bottle.app()
#app = SessionMiddleware(bottle.app(), config.SESSION_OPTS)
def main():

    # Start the Bottle webapp
    bottle.debug(True)
    bottle.run(app=app, quiet=False, reloader=False)
Example #56
0
from sys import argv

import bottle
from bottle import *

bottle.debug(true)

@route("/")
def index():
    return "Halló heimur"

bottle.run(host= '0,0,0,0', port=argv(1)


Example #57
0
import os
import cPickle as pickle
from pprint import pprint
import bottle
import beaker.middleware
from bottle import route, redirect, post, run, request, hook
from instagram import client, subscriptions
import networkx as nx
import wholikes as wl
bottle.debug(False)

session_opts = {
    'session.type': 'file',
    'session.data_dir': './session/',
    'session.auto': True,
}

app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)
access_token = None

CONFIG = {
    'client_id': 'f2ad558000f54a519d11c47c1ae8cc70',
    'client_secret': '8ef039d5b72646378e9a034ca9039a0c',
    'redirect_uri': 'http://localhost:8515/oauth_callback'
}

unauthenticated_api = client.InstagramAPI(**CONFIG)


def get_nav():
    nav_menu = (
Example #58
0
#shrani spremembe pri urejanju tupa hranila
@app.route('/nutrient-type-edit/<id>', method='POST')
def nutrient_types_edit_post(id, db):
    title = request.forms.get('title')
    q = """UPDATE nutrient_type SET title=:title WHERE id=:id;"""
    c = db.execute(q, {'title': title, 'id': id})
    if (c.rowcount > 0):
        redirect('/nutrient-types?changes=updated')


#prikaze tip hranila
@app.route('/nutrient-type/<id>')
def nutrient_type(id, db):
    q = "SELECT * FROM nutrient_type WHERE id=:id;"
    c = db.execute(q, {'id': id})
    nutrient_type = c.fetchone()
    return template('nutrient-type-details.tpl', nt=nutrient_type)


#izbrise tip hranila
@app.route('/nutrient-type-delete/<id>')
def nutrient_type_delete(id, db):
    q = "DELETE FROM nutrient_type WHERE id=:id;"
    c = db.execute(q, {'id': id})
    if (c.rowcount > 0):
        redirect('/nutrient-types?changes=deleted')


debug(True)  #piše errorje
run(app, host='localhost', port=8080, reloader=True)
Example #59
0
def main():
    bottle.debug(DEBUG)
    run(host='0.0.0.0', port=5723)
Example #60
0
from bottle import route, run, debug, default_app, response, request
from urllib.parse import urlencode
import json
import os

TOKEN = os.getenv('TOKEN', None)
PORT = int(os.getenv('PORT', 8000))


@route('/', method='POST')
def index():
    text = request.forms.get('text')
    token = request.forms.get('token')
    if token and token != TOKEN:
        return ""
    if not text:
        return "You should probably tell me to google something for someone."
    lmgtfy_url = "http://lmgtfy.com/?" + urlencode({'q': text})
    response.content_type = 'application/json'
    return json.dumps({
        'response_type': 'in_channel',
        'text': "Please, <" + lmgtfy_url + "|allow me!>"
    })


app = default_app()

debug(False)
run(host='0.0.0.0', port=PORT, reloader=True)