Ejemplo n.º 1
0
 def serve(self, host='0.0.0.0', port=8080):
     """
     Launch the WSGI app development web server
     """
     import waitress
     logger.info("{}:{}".format(host, port))
     waitress.serve(self.app, host=host, port=port, _quiet=True)
Ejemplo n.º 2
0
def wsgi_run(app, opts, args):
    """ """

    serve(app,
          host=opts.host,
          port=opts.port
    )
Ejemplo n.º 3
0
def server_command(args):
    repository = args.repository
    app.config.update(REPOSITORY=repository, SESSION_ID=args.session_id)
    app.debug = args.debug
    if args.no_worker:
        app.config.update(USE_WORKER=False)
    if args.profile:
        try:
            from linesman.middleware import make_linesman_middleware
        except ImportError:
            print('-P/--profile/--linesman option is available only when '
                  "linesman is installed", file=sys.stderr)
            print('Try the following command:', file=sys.stderr)
            print('\tpip install linesman', file=sys.stderr)
            raise SystemExit
        else:
            print('Profiler (linesman) is available:',
                  'http://{0.host}:{0.port}/__profiler__/'.format(args))
        app.wsgi_app = make_linesman_middleware(app.wsgi_app)
    if args.debug:
        app.wsgi_app = SassMiddleware(app.wsgi_app, {
            'earthreader.web': ('static/scss/', 'static/css/')
        })
        app.run(host=args.host, port=args.port, debug=args.debug,
                threaded=True)
    else:
        serve(app, host=args.host, port=args.port)
Ejemplo n.º 4
0
 def run(self, host='127.0.0.1', port=5000):
     from waitress import serve
     try:
         serve(self, host=host, port=port)
     except Exception as e:
         raise RuntimeError("Unable to start server on "
                            "{}:{} ({})".format(host, port, e))
Ejemplo n.º 5
0
def start(args, kill = None):
    config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pywps.cfg")

    processes = [
        FeatureCount(),
        SayHello(),
        Centroids(),
        UltimateQuestion(),
        Sleep(),
        Buffer(),
        Area(),
        Box(),
        Warp()
    ]

    s = Server(processes=processes, config_file=config_file)

    # TODO: need to spawn a different process for different server
    if args.waitress:
        import waitress
        from pywps import configuration

        configuration.load_configuration(config_file)
        host = configuration.get_config_value('wps', 'serveraddress').split('://')[1]
        port = int(configuration.get_config_value('wps', 'serverport'))

        waitress.serve(s.app, host=host, port=port)
    else:
        s.run()
Ejemplo n.º 6
0
def api_server(ctx, bind, workers):
    """
    Starts the nidaba API server using gunicorn.
    """

    try:
        from nidaba import api
        from nidaba import web
    except IOError as e:
        if e.errno == 2:
            click.echo('No configuration file found at {}'.format(e.filename))
            ctx.exit()

    import logging

    from waitress import serve
    from flask import Flask

    logging.basicConfig(level=logging.DEBUG)

    app = Flask('nidaba')
    app.register_blueprint(api.get_blueprint())
    app.register_blueprint(web.get_blueprint())
    
    serve(app, listen=' '.join(bind).encode('utf-8'), threads=workers)
Ejemplo n.º 7
0
def main():
 
    api = falcon.API()
    api.add_route('/heka', HekaEndPoint())   


    serve(api, host='0.0.0.0', port=6227, _quiet=False)
Ejemplo n.º 8
0
def Main():
  args = ParseArguments()

  if args.stdout is not None:
    sys.stdout = open( args.stdout, 'w' )
  if args.stderr is not None:
    sys.stderr = open( args.stderr, 'w' )

  SetupLogging( args.log )
  options = SetupOptions( args.options_file )

  # This ensures that ycm_core is not loaded before extra conf
  # preload was run.
  YcmCoreSanityCheck()
  extra_conf_store.CallGlobalExtraConfYcmCorePreloadIfExists()
  PossiblyDetachFromTerminal()

  # This can't be a top-level import because it transitively imports
  # ycm_core which we want to be imported ONLY after extra conf
  # preload has executed.
  from ycmd import handlers
  handlers.UpdateUserOptions( options )
  SetUpSignalHandler(args.stdout, args.stderr, args.keep_logfiles)
  handlers.app.install( WatchdogPlugin( args.idle_suicide_seconds ) )
  handlers.app.install( HmacPlugin( options[ 'hmac_secret' ] ) )
  CloseStdin()
  waitress.serve( handlers.app,
                  host = args.host,
                  port = args.port,
                  threads = 30 )
Ejemplo n.º 9
0
def main():
    parser = argparse.ArgumentParser(
        description=('Command-line interface for running the '
                     'RasmusMediaWeb server'),
    )
    parser.add_argument(
        '-p', '--port',
        default='8888',
        help='Port to listen on (default: 8888)',
    )
    parser.add_argument(
        '-i', '--interface',
        default='0.0.0.0',
        help='Interface to listen on (default: 0.0.0.0)',
    )
    parser.add_argument(
        '--prefix',
        help='Serve app at a prefixed url',
    )
    args = parser.parse_args()

    kwargs = {
        'host': args.interface,
        'port': args.port,
    }
    if args.prefix:
        kwargs['url_prefix'] = args.prefix

    serve(make_app(), **kwargs)
Ejemplo n.º 10
0
def takedown_app(env, parsed_ns):
    try:
        from waitress import serve
    except ImportError:
        print("Waitress needed to run this script")
        raise
    _waitress_console_logging()
    config = Configurator()
    config.include('pyramid_chameleon')
    msg = "We'll be back shortly. Sorry for the inconvenience!"
    if parsed_ns.message:
        msg = parsed_ns.message.decode('utf-8')
    #Figure out template path
    if ':' in parsed_ns.template or parsed_ns.template.startswith('/'):
        tpl = parsed_ns.template
    else:
        #Expect relative path
        tpl = os.path.join(os.getcwd(), parsed_ns.template)
        view = TakedownView(msg, tpl)
        #Test rendering to cause exception early
        view(env['request'])
        print ("Serving template from: %s" % tpl)
    takedown_view = TakedownView(msg, tpl)
    config.add_view(takedown_view, context=HTTPNotFound)
    print("Takedown app running... press ctrl+c to quit")
    app = config.make_wsgi_app()
    #Figure out port or socket
    kwargs = {}
    if ':' in parsed_ns.listen:
        kwargs['listen'] = parsed_ns.listen
    else:
        kwargs['unix_socket'] = parsed_ns.listen
        kwargs['unix_socket_perms'] = '666'
    serve(app, **kwargs)
Ejemplo n.º 11
0
def server(reload=False):
    "Run the server"
    if reload:
        reload_me("server")
    else:
        serve(app, host=app.config["HOST"], port=app.config["PORT"], 
                threads=app.config["THREADS"])
Ejemplo n.º 12
0
def main():
    insta = Instagram()
    recent_instagrams = insta.recent_images()
    
    app = create_app()
    serve(app, port=9845)
    
def run():
    if len(sys.argv) != 2:
        sys.stderr.write("Usage: %s <config_file>\n" % (sys.argv[0],))
        sys.exit(1)

    settings = {'db_filename': './acss.db', 'server_host': 'localhost',
        'server_port': 8081}
    settings.update(json.loads(open(sys.argv[1]).read()))

    config = Configurator(settings=settings)

    def add_db(request, reify=True):
        return DB(request.registry.settings.get('db_filename'))

    config.add_request_method(add_db, 'db')

    config.add_route('api_tracks', '/api/tracks')
    config.add_route('api_track_bestlaps', '/api/tracks/{track_name}/bestlaps')
    config.add_route('api_track_bestlaps_with_cars', '/api/tracks/{track_name}/{car_names}/bestlaps')
    config.add_route('api_server_info', '/api/server_info')

    config.add_view(api_tracks, route_name='api_tracks', renderer='json')
    config.add_view(api_track_bestlaps, route_name='api_track_bestlaps',
        renderer='json')
    config.add_view(api_track_bestlaps_with_cars,
        route_name='api_track_bestlaps_with_cars', renderer='json')
    config.add_view(api_server_info, route_name='api_server_info',
        renderer='json')

    app = config.make_wsgi_app()
    serve(app, host='0.0.0.0', port=8001)
Ejemplo n.º 14
0
Archivo: demo.py Proyecto: keceke/pywps
def main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('-w', '--waitress', action='store_true')
    args = parser.parse_args()

    config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pywps.cfg")

    processes = [
        FeatureCount(),
        SayHello(),
        Centroids(),
        UltimateQuestion(),
        Sleep(),
        Buffer(),
        Area(),
        Viewshed()
    ]

    s = Server(processes=processes, config_file=config_file)

    # TODO: need to spawn a different process for different server
    if args.waitress:
        import waitress
        from pywps import configuration

        configuration.load_configuration(config_file)
        host = configuration.get_config_value('wps', 'serveraddress').split('://')[1]
        port = int(configuration.get_config_value('wps', 'serverport'))

        waitress.serve(s.app, host=host, port=port)
    else:
        s.run()
Ejemplo n.º 15
0
def run_server(config):
    setup_app(config)
    setup_logging(config)

    # Initialize huey task queue
    global task_queue
    db_location = os.path.join(config.config_dir(), 'queue.db')
    task_queue = SqliteHuey(location=db_location)
    consumer = Consumer(task_queue)

    ip_address = get_ip_address()
    if (app.config['standalone'] and ip_address
            and config['driver'].get() in ['chdkcamera', 'a2200']):
        # Display the address of the web interface on the camera displays
        try:
            for cam in get_devices(config):
                cam.show_textbox(
                    "\n    You can now access the web interface at:"
                    "\n\n\n         http://{0}:5000".format(ip_address))
        except:
            logger.warn("No devices could be found at startup.")

    # Start task consumer
    consumer.start()
    try:
        import waitress
        # NOTE: We spin up this obscene number of threads since we have
        #       some long-polling going on, which will always block
        #       one worker thread.
        waitress.serve(app, port=5000, threads=16)
    finally:
        consumer.shutdown()
        if app.config['DEBUG']:
            logger.info("Waiting for remaining connections to close...")
Ejemplo n.º 16
0
    def run(self):
        bottle_app = bottle.app()

        # Initialize the app context
        app_context = [ApiController()]

        # Serve the api
        waitress.serve(bottle_app, host='0.0.0.0', port=8080)
Ejemplo n.º 17
0
def run_server(f, port):
    global folder_to_save_data, port_for_server
    if f != None:
        folder_to_save_data = abspath(f)
    if port != None:
        port_for_server = port
    print("\n\nStarting server, saving data to %s" % folder_to_save_data)
    serve(app, listen='*:' + port_for_server)
Ejemplo n.º 18
0
Archivo: run.py Proyecto: eevee/spline
def serve_app(parser, args):
    app = spline.app.main({}, **vars(args))
    if args.bind:
        import waitress
        waitress.serve(app, **args.bind)
    else:
        # TODO this is for playing nicely with uwsgi's paste-serve, but will
        # just quietly exit if you run directly as CLI, oops?
        return app
Ejemplo n.º 19
0
Archivo: cli.py Proyecto: machawk1/pywb
 def run(self):
     try:
         from waitress import serve
         print(self.desc)
         serve(self.application, port=self.r.port, threads=self.r.threads)
     except ImportError:  # pragma: no cover
         # Shouldn't ever happen as installing waitress, but just in case..
         from pywb.framework.wsgi_wrappers import start_wsgi_ref_server
         start_wsgi_ref_server(self.application, self.desc, port=self.r.port)
Ejemplo n.º 20
0
def main():
    Bot.load()
    bot = Bot_Template()

    try:
        import waitress
        waitress.serve(bot.application)
    finally:
        bot.close()
Ejemplo n.º 21
0
def main():
    engine = sqlalchemy.create_engine('sqlite:///morepath_react.db')
    Session.configure(bind=engine)
    Base.metadata.create_all(engine)
    Base.metadata.bind = engine

    morepath.autosetup()
    app = App()
    waitress.serve(app)
Ejemplo n.º 22
0
def main():
    parser = make_parser()
    args = parser.parse_args()

    app = spline.app.main({}, **vars(args))
    if args.bind:
        waitress.serve(app, **args.bind)
    else:
        return app
Ejemplo n.º 23
0
def main():
  engine = sqlalchemy.create_engine('sqlite:///morepath_sqlalchemy.db')
  Session.configure(bind=engine)
  Base.metadata.create_all(engine)
  Base.metadata.bind = engine

  morepath.autosetup()
  wsgi = App()
  waitress.serve(App(), host="localhost")
Ejemplo n.º 24
0
def Main():
    args = ParseArgs()

    if args.hmac_file_secret:
        hmac_secret = GetSecretFromTempFile(args.hmac_file_secret)
        handlers.app.config["jedihttp.hmac_secret"] = b64decode(hmac_secret)
        handlers.app.install(HmacPlugin())

    serve(handlers.app, host=args.host, port=args.port)
Ejemplo n.º 25
0
Archivo: command.py Proyecto: 0hoo/web
def server_command(args):
    repository = args.repository
    app.config.update(REPOSITORY=repository, SESSION_ID=args.session_id)
    app.debug = args.debug
    spawn_worker()
    if args.debug:
        app.run(host=args.host, port=args.port, debug=args.debug, threaded=True)
    else:
        serve(app, host=args.host, port=args.port)
Ejemplo n.º 26
0
def main():
    document = load_document_yaml('core_module.yaml')

    api = falcon.API()
    api.add_route('/ui', UIResource())
    api.add_route('/format/aspect', AspectFormatResource(document))
    api.add_route('/format/character', CharacterFormatResource(document))

    waitress.serve(api, host='0.0.0.0', port=8080)
Ejemplo n.º 27
0
def main():
    # set up morepath's own configuration
    config = morepath.setup()
    # load application specific configuration
    config.scan()
    config.commit()

    # serve app as WSGI app
    waitress.serve(app())
Ejemplo n.º 28
0
def Main():
  parser = argparse.ArgumentParser()
  parser.add_argument( '--host', type = str, default = 'localhost',
                       help = 'server hostname')
  # Default of 0 will make the OS pick a free port for us
  parser.add_argument( '--port', type = int, default = 0,
                       help = 'server port')
  parser.add_argument( '--log', type = str, default = 'info',
                       help = 'log level, one of '
                              '[debug|info|warning|error|critical]' )
  parser.add_argument( '--idle_suicide_seconds', type = int, default = 0,
                       help = 'num idle seconds before server shuts down')
  parser.add_argument( '--options_file', type = str, default = '',
                       help = 'file with user options, in JSON format' )
  parser.add_argument( '--stdout', type = str, default = None,
                       help = 'optional file to use for stdout' )
  parser.add_argument( '--stderr', type = str, default = None,
                       help = 'optional file to use for stderr' )
  parser.add_argument( '--keep_logfiles', action = 'store_true', default = None,
                       help = 'retain logfiles after the server exits' )
  args = parser.parse_args()

  if args.stdout is not None:
    sys.stdout = open(args.stdout, "w")
  if args.stderr is not None:
    sys.stderr = open(args.stderr, "w")

  numeric_level = getattr( logging, args.log.upper(), None )
  if not isinstance( numeric_level, int ):
    raise ValueError( 'Invalid log level: %s' % args.log )

  # Has to be called before any call to logging.getLogger()
  logging.basicConfig( format = '%(asctime)s - %(levelname)s - %(message)s',
                       level = numeric_level )

  options = ( json.load( open( args.options_file, 'r' ) )
              if args.options_file
              else user_options_store.DefaultOptions() )
  user_options_store.SetAll( options )

  # This ensures that ycm_core is not loaded before extra conf
  # preload was run.
  YcmCoreSanityCheck()
  extra_conf_store.CallGlobalExtraConfYcmCorePreloadIfExists()

  # This can't be a top-level import because it transitively imports
  # ycm_core which we want to be imported ONLY after extra conf
  # preload has executed.
  from ycm.server import handlers
  handlers.UpdateUserOptions( options )
  SetUpSignalHandler(args.stdout, args.stderr, args.keep_logfiles)
  handlers.app.install( WatchdogPlugin( args.idle_suicide_seconds ) )
  waitress.serve( handlers.app,
                  host = args.host,
                  port = args.port,
                  threads = 30 )
Ejemplo n.º 29
0
def main_2():
    opts, args = parse_args()
    config = Configuration.from_file(opts.conf)
    app = make_app(config)
    app.debug = True

    from waitress import serve
    serve(app.wsgi_app, host=opts.host,
          port=opts.port
          )
Ejemplo n.º 30
0
Archivo: app.py Proyecto: nrc/highfive
def cli(port, github_token, webhook_secret, config_dir):
    try:
        config = Config(github_token)
    except InvalidTokenException:
        print('error: invalid github token provided!')
        sys.exit(1)
    print('Found a valid GitHub token for user @' + config.github_username)

    app = create_app(config, webhook_secret, config_dir)
    waitress.serve(app, port=port)
Ejemplo n.º 31
0
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp
from waitress import serve

app = Flask(__name__)

try:
    ISSUER_URL = os.environ["ISSUER_URL"]
    AUTH_URL = os.environ["AUTH_URL"]
    TOKEN_URL = os.environ["TOKEN_URL"]
    USERINFO_URL = os.environ["USERINFO_URL"]
    JWKS_URL = os.environ["JWKS_URL"]
except Exception as ex:
    raise

@app.route('/')
def index():
    return 'Hello world!'

@app.route("/login")
def login():
    return redirect(AUTH_URL, code=302)

@app.route("/auth/callback")
def custom_callback():
    return "Logged in!"

if __name__ == "__main__":
    serve(app, host='0.0.0.0', port='8000')

Ejemplo n.º 32
0
    assert_welcome()
    tickers = request.args['tickers'].replace(';', '\n').replace(',', '\n').replace(' ', '\n').split('\n')
    tickers = [t for t in tickers if t]
    dataset = re.sub(r'[^\w_\.]','', request.args['name'].replace('.csv', ''))
    today = datetime.datetime.now().date().isoformat()
    with open(os.path.join('lists', f'{dataset}_{today}.json'), 'w') as w:
        json.dump(tickers, w)
    ScheduledFinance(dataset, today, tickers)
    app.logger.info('Job added.')
    return 'JOB ADDED'

@app.route('/get_tickers')
def get_tickers():
    assert_welcome()
    file = os.path.split(request.args['dataset'])[1] + '.json'
    if not os.path.exists(os.path.join('lists', file)):
        abort(404, description="File not found")
    else:
        return '\n'.join(json.load(open(os.path.join('lists', file))))

if __name__ == '__main__':
    try:
        serve(app, port=8041)
    except Exception as error:
        msg = f'LETHAL: {type(error).__name__}: {error}.'
        print(msg)
        import logging
        logger = logging.getLogger(__name__)
        logger.critical(msg)
        ScheduledFinance.__new__(ScheduledFinance).slack(msg)
Ejemplo n.º 33
0
'''
Single-File Web Applications
'''

from waitress import serve
from pyramid.config import Configurator
from pyramid.response import Response


def hello_world(request):
    '''
    Implement the view code that generates the response.
    '''
    print('Incoming request')
    return Response('<body><h1>Hello World!</h1></body>')


if __name__ == '__main__':
    # Use Pyramid's configurator in a context manager to connect view code to a particular URL route.
    with Configurator() as config:
        config.add_route('posts', '/')
        config.add_view(hello_world, route_name='posts')
        app = config.make_wsgi_app()
    # Publish a WSGI app using an HTTP server.
    serve(app, host='0.0.0.0', port=6543)
Ejemplo n.º 34
0
def get_unfulfilled_receipts():
    limit = int(request.args.get('limit', '50'))
    offset = int(request.args.get('offset', '0'))
    return do_unfulfilled_receipts(limit, offset)


def worker_thread():
    config = load_config_non_flask()
    url_template = None
    is_debug = 'DEBUG' in config and config['DEBUG'] == 'True'
    is_printer_debug = 'PRINTER_DEBUG' in config and config[
        'PRINTER_DEBUG'] == 'True'
    sleep_interval = float(config.get('SLEEP_INTERVAL', '60'))  # seconds
    while True:
        update_printers(is_printer_debug, is_debug)
        sleep(sleep_interval)


def setup():
    threading.Thread(target=worker_thread, daemon=True).start()


if __name__ == '__main__':
    setup()
    from waitress import serve
    local_ip = get_local_ip()
    print('%s:%s' % (local_ip, 80))
    import webbrowser
    webbrowser.open('http://%s' % local_ip)
    serve(app, host=local_ip, port=80, threads=16)
Ejemplo n.º 35
0
def launch_server(command, **options):

    # Migrate the database.
    cmd_args = {'noinput': True}
    if options['database']:
        cmd_args['database'] = options['database']
    management.call_command('migrate', **cmd_args)

    create_users()
    models_fix_data()
    try:
        reset_font_cache()
    except:
        pass

    # Initialize the database with pre-seeded data if it was not done.
    init_data_if_necessary()

    # Read the config file and adjust any options.
    config_parser = SafeConfigParser()
    try:
        with open(options['config'], 'r') as fp:
            config_parser.readfp(fp, options['config'])
        safe_print(u'Read config file "{}".'.format(options['config']))
    except Exception as e:
        if options['config'] != 'RaceDB.cfg':
            safe_print(u'Could not parse config file "{}" - {}'.format(
                options['config'], e))
        config_parser = None

    if config_parser:
        kwargs = KWArgs()
        command.add_arguments(kwargs)
        for arg, value in list(options.items()):
            try:
                config_value = config_parser.get('launch', arg)
            except NoOptionError:
                continue

            config_value, error = kwargs.validate(arg, config_value)
            if error:
                safe_print(u'Error: {}={}: {}'.format(arg, config_value,
                                                      error))
                continue

            options[arg] = config_value
            safe_print(u'    {}={}'.format(arg, config_value))

    if options['hub']:
        set_hub_mode(True)
        safe_print(u'Hub mode.')

    # Start the rfid server.
    if not options['hub'] and any([
            options['rfid_reader'], options['rfid_reader_host'],
            options['rfid_transmit_power'] > 0,
            options['rfid_receiver_sensitivity'] > 0
    ]):
        kwargs = {
            'llrp_host': options['rfid_reader_host'],
        }
        if options['rfid_transmit_power'] > 0:
            kwargs['transmitPower'] = options['rfid_transmit_power']
        if options['rfid_receiver_sensitivity'] > 0:
            kwargs['receiverSensitivity'] = options[
                'rfid_receiver_sensitivity']
        safe_print(u'Launching RFID server thread...')
        for k, v in kwargs.iteritems():
            safe_print(u'    {}={}'.format(
                k, v if isinstance(v,
                                   (int, long, float)) else '"{}"'.format(v)))
        thread = threading.Thread(target=runServer, kwargs=kwargs)
        thread.name = 'LLRPServer'
        thread.daemon = True
        thread.start()
        time.sleep(0.5)

    connection_good = check_connection(options['host'], options['port'])

    if not options['no_browser']:
        if not connection_good:
            safe_print(
                u'Attempting to launch broswer connecting to an existing RaceDB server...'
            )

        # Schedule a web browser to launch a few seconds after starting the server.
        url = 'http://{}:{}/RaceDB/'.format(
            socket.gethostbyname(socket.gethostname()), options['port'])
        threading.Timer(3.0 if connection_good else 0.01,
                        webbrowser.open,
                        kwargs=dict(url=url, autoraise=True)).start()
        safe_print(
            u'A browser will be launched in a few moments at: {}'.format(url))

    if connection_good:
        safe_print(
            u'To stop the server, click in this window and press Ctrl-c.')

        # Add Cling to serve up static files efficiently.
        serve(Cling(RaceDB.wsgi.application),
              host=options['host'],
              port=options['port'],
              threads=10,
              clear_untrusted_proxy_headers=False)
    else:
        time.sleep(0.5)
Ejemplo n.º 36
0
 def run(self):
     serve(self.app, host=self.host, port=self.port)
Ejemplo n.º 37
0
#!/usr/bin/env python3
from flask import Flask, jsonify
from waitress import serve # Import waitress, to use instead of Flask's default webserver
app = Flask(__name__)

stuff = { 
        'people': ['John', 'Jacob', 'Jinklheimer', 'Smith', 'Bob'], 
        'places': ['Chicago', 'Los Vegas', 'New York', 'Hell'],
        'things': ['Pumkin', 'Spice', 'Puppies', 'Kittens', 'Weed'],
        }

@app.route('/', defaults={ 'lookup': None })
@app.route('/<string:lookup>')
def smarter_path(lookup):
    if lookup:
        return jsonify(stuff[lookup])
    return stuff

serve(app) # This is the only thing that changed besides the import.
           # It seems to default to port 8080 instead of 5000. 
           # It may bitch about favicon.ico not being found. 
           # That's fine, favicon.ico is the little icon that shows up in your address bar when you go to a page.
Ejemplo n.º 38
0
    application.logger.info("Starting webdav v{}.".format(version))
    application.logger.info("Using '{}' environment settings.".format(
        settings.environment))
    application.logger.info("Enabled storages: {}.".format(
        settings.ENABLED_STORAGES.keys()))

    return application


if __name__ == '__main__':

    application = create_app()
    deploy_via = application.config['DEPLOY_VIA']
    host = '0.0.0.0'
    port = os.environ.get('PORT', 8080)

    application = DispatcherMiddleware(application, {'/webdav': application})

    if deploy_via == 'waitress':
        from waitress import serve
        serve(application, host=host, port=port)
    elif deploy_via == 'werkzeug':
        from werkzeug.serving import run_simple
        run_simple(hostname=host,
                   port=port,
                   application=application,
                   use_reloader=True)
    else:
        print("No valid deployment option specified!")
        sys.exit(1)
Ejemplo n.º 39
0
from waitress import serve
import app
if __name__ == '__main__':
    serve(app.app, host='0.0.0.0', port=8080)
Ejemplo n.º 40
0
def run_web_server():
    """ Starts the web server """
    serve(_APP, port=config.CONSTANTS["WEB_PORT"])
Ejemplo n.º 41
0
from waitress import serve

from flask import Flask
app = Flask(__name__)


@app.route('/')
def hello():
    return "Hello World!"

if __name__ == '__main__':
    serve(app, listen='*:8080')
Ejemplo n.º 42
0
app = Flask(__name__)
app.config.from_mapping(DEBUG=False, TESTING=False)
robot = CmdUI()


@app.route('/chatbot/api/chat', methods=['POST'])
def chat():
    try:
        data = request.get_data()
        json_re = json.loads(data)
        print(data, json_re)
        context = {"state": json_re["state"], "buffer": json_re["buffer"]}

        context = robot.context_input(json_re["message"], context)
        print(context)
        return json.dumps({
            "ok": True,
            "state": context["state"],
            "buffer": context["buffer"],
            "messages": robot.get_outputs()
        })

    except Exception as e:
        print(e)
        return json.dumps({"ok": False})


if __name__ == '__main__':
    from waitress import serve
    serve(app, host="0.0.0.0", port=3001)
Ejemplo n.º 43
0
                    'pType':pType,
                    'productCode': productCode,
                    'purchasedOn':purchasedOn,
                    'warrantTill' : warranty_till}}})
                return jsonify({'result' : 'product added sucessfully'})
            else:
                return jsonify({'result' : 'problem to activate product warranty!'})
        else:
            return jsonify({'result' : 'productCode already exists!'})
                


if __name__ == '__main__':
    #app.run(debug=True, host='0.0.0.0')
    from waitress import serve
    serve(app, host="0.0.0.0", port=5000)













'''
Ejemplo n.º 44
0
import falcon
import falcon_jsonify
import mongoengine as mongo

import server.settings as settings
from server.resources.example import ExampleResource
from server.middleware.auth import AuthHandler
from server.resources.base import base
from server.resources import user
from server.middleware.json_translator import JSONTranslator


class App(falcon.API):
    def __init__(self, *args, **kwargs):
        super(App, self).__init__(*args, **kwargs)
        self.add_route('/api', ExampleResource())
        self.add_route('/', base.BaseResource())
        self.add_route('/register', user.Collection())
        self.add_route('/manage/login', user.Manage_Account())
        self.add_route('/manage/resetpsw', user.Manage_Account())


middleware = [AuthHandler(), JSONTranslator()]
api = App(middleware=middleware)
#  falcon_jsonify.Middleware(help_messages=settings.DEBUG)

if __name__ == "__main__":
    from waitress import serve

    serve(api, host="127.0.0.1", port=8000)
Ejemplo n.º 45
0
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from waitress import serve
from paste.translogger import TransLogger

from app import app
from apps import app_home, app_moneyfacts

app.layout = html.Div(
    [dcc.Location(id='url', refresh=True),
     html.Div(id='page-content')])


@app.callback(Output('page-content', 'children'), Input('url', 'pathname'))
def display_page(pathname):
    if pathname == '/moneyfacts':
        return app_moneyfacts.serve_layout()
    else:
        return app_home.serve_layout()


if __name__ == '__main__':
    # app.run_server(debug=True, host='AUD0100CK4', port=8084)
    serve(TransLogger(app.server, logging_level=30),
          host='AUD0100CK4',
          port=8084)
Ejemplo n.º 46
0
import waitress
import app

waitress.serve(app.app, port=5000, threads=4)
Ejemplo n.º 47
0
import os
from waitress import serve
from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pizza.settings")

application = get_wsgi_application()

serve(application, port=os.environ["PORT"])
Ejemplo n.º 48
0
# Main Thread
if __name__ == '__main__':

    # Get configuration file
    conf = json.load(open("pyconf/conf.json"))

    # filter warnings, load the configuration and initialize the Dropbox client
    warnings.filterwarnings("ignore")
    client = None

    # load the known faces and embeddings along with OpenCV's Haar
    # cascade for face detection
    data = pickle.loads(open(conf["encodings"], "rb").read())
    detector = cv2.CascadeClassifier(conf["cascade"])
    print("[SUCCESS] encodings + face detector loaded")

    # start a thread that will perform motion detection
    t = threading.Thread(target=compute_frames)
    t.daemon = True
    t.start()

    ### run development server
    # os.environ["FLASK_ENV"] = "development"
    ## start the flask app
    # app.run(host=conf["ip_address"], port=conf["port"], debug=True, threaded=True, use_reloader=False)
    ### run production server
    serve(app, host=conf['ip_address'], port=conf['port'])

# release the video stream
vs.stop()
Ejemplo n.º 49
0
from waitress import serve

from newProject.wsgi import application

if __name__ == '__main__':
    serve(application, host='localhost', port='8080')
Ejemplo n.º 50
0
# encoding: utf-8
from flask_script import Manager
from waitress import serve

from people.app import create_app

app = create_app()

if __name__ == '__main__':
    serve(app, host='0.0.0.0', port=8081)
from tenderloin.app import create_app
from tenderloin.config.app_config import ProductionAppconfig
from tenderloin.config.db_config import RemoteDBConfig
from tenderloin.const.run_setting import RUN_SETTINGS

if __name__ == "__main__":
    app = create_app(ProductionAppconfig, RemoteDBConfig)

    from waitress import serve

    serve(app, **RUN_SETTINGS)
Ejemplo n.º 52
0
        global userin
        global server_reg_key
        global db_session
        nlp = nlp_ref  # Load en_core_web_sm, English, 50 MB, default model
        learner = learner_ref
        odqa = odqa_ref
        dc = dc_ref
        coref = coref_ref
        userin = userin_ref
        server_reg_key = reg_key
        db_session = db_session_ref
        app = hug.API(__name__)
        app.http.output_format = hug.output_format.text
        app.http.add_middleware(CORSMiddleware(app))
        self.waitress_thread = Thread(target=waitress.serve,
                                      args=(__hug_wsgi__, ),
                                      kwargs={"port": port_number})
        if dont_block:
            self.waitress_thread.daemon = True
        self.waitress_thread.start()
        if not dont_block:
            self.waitress_thread.join()


if __name__ == '__main__':
    global __hug_wsgi__  # Fixes flake8 F821: Undefined name
    app = hug.API(__name__)
    app.http.output_format = hug.output_format.text
    app.http.add_middleware(CORSMiddleware(app))
    waitress.serve(__hug_wsgi__, port=8000)
Ejemplo n.º 53
0

##
# Queue deadlock error debug page.
@app.route('/queue_clear')
def queue_clear():
    while not requests_queue.empty():
        requests_queue.get()

    return "Clear", 200


##
# Sever health checking page.
@app.route('/healthz', methods=["GET"])
def health_check():
    return "Health", 200


##
# Main page.
@app.route('/')
def main():
    return render_template('index.html'), 200


if __name__ == '__main__':
    from waitress import serve
    app.logger.info("server start")
    serve(app, port=80, host='0.0.0.0')
Ejemplo n.º 54
0
    stop_sig = True
    set_value("status", "mode", 3)
    set_value("status", "turn", 0)
    return 'Stopped'


@app.route('/')
def mainpage():
    return 'Go to init'


for i in range(n_team + 1):
    item_set_av.append([])
    for j in range(n_node + 1):
        item_set_av[i].append([])
        for k in range(3):
            item_set_av[i][j].append(0)

db.reference("winner").delete()
set_value("status", "mode", 3)
set_value("status", "turn", 0)
for i in range(n_node):
    for j in range(3):
        if (mp.g[i + 1].items[j][0] in [9, 10, 11]) or (mp.g[i + 1].items[j][1]
                                                        in [20, 21]):
            item_set_left[i + 1][j] = 3

update_database()
if __name__ == "__main__":
    serve(app, host='0.0.0.0', port=5555, threads=26)
Ejemplo n.º 55
0
proxy = 'http://127.0.0.1:8080/auth/v1.0'
insecure = False  # Set to True to disable SSL certificate validation

config = wsgidav_app.DEFAULT_CONFIG.copy()
config.update({
    "provider_mapping": {
        "": swiftdav.SwiftProvider()
    },
    "verbose":
    1,
    "propsmanager":
    True,
    "locksmanager":
    True,
    "acceptbasic":
    True,
    "acceptdigest":
    False,
    "defaultdigest":
    False,
    "domaincontroller":
    swiftdav.WsgiDAVDomainController(proxy, insecure)
})
app = wsgidav_app.WsgiDAVApp(config)

waitress.serve(app,
               host="0.0.0.0",
               port=8000,
               max_request_body_size=5 * 1024 * 1024 * 1024)
Ejemplo n.º 56
0

def verify_fb_token(token_sent):
    #take token sent by facebook and verify it matches the verify token you sent
    #if they match, allow the request, else return an error
    if token_sent == VERIFY_TOKEN:
        return request.args.get("hub.challenge")
    return 'Invalid verification token'


#chooses a random message to send to the user
def get_message():
    sample_responses = [
        "You are stunning!", "We're proud of you.", "Keep on being you!",
        "We're greatful to know you :)"
    ]
    # return selected item to the user
    return random.choice(sample_responses)


#uses PyMessenger to send response to user
def send_message(recipient_id, response):
    #sends user the text message provided via input response parameter
    bot.send_text_message(recipient_id, response)
    return "success"


if __name__ == "__main__":
    #app.run()
    serve(app, port=5000)
Ejemplo n.º 57
0
@app.route("/gettimeseriestags")
def getTimeSeriesTags():
    if reonService.verify_auth_token(request.args.get('tok')):
        return assets.get_timeseries_tags()
    abort(make_response(jsonify(Auth_Token_Expired), 401))


@app.route("/putalltags")
def putAllTags():
    if reonService.verify_auth_token(request.args.get('tok')):
        classifier = request.args.get('t')
        classifier_id = request.args.get('id')
        new_value = request.args.get('v')
        return make_response(jsonify({'message': 'Tag Inserted'}), 201)
    abort(make_response(jsonify(Auth_Token_Expired), 401))


@app.route("/deletetags")
def deleteTags():
    if reonService.verify_auth_token(request.args.get('tok')):
        classifier = request.args.get('t')
        classifier_id = request.args.get('id')
        old_value = request.args.get('v')
        return make_response(jsonify({'message': 'Tag Deleted'}), 201)
    abort(make_response(jsonify(Auth_Token_Expired), 401))


if __name__ == "__main__":
    # app.run(host='0.0.0.0', port=port)
    serve(app, host='0.0.0.0', port=port)
Ejemplo n.º 58
0
    # instantiate a new object of this class
    if settings.get_settings("ACCEPT_STATS"):
        cls(**data)
        db.save()
    else:
        log("Not accepting any stats right now.")


@server.get("/<endpoint>")
def get_endpoint(endpoint):
    try:
        cls = db._getclassbyname(endpoint)
        # return information
        return {
            "types": {
                t: reverse_typenames[cls.__annotations__[t]]
                for t in cls.__annotations__
            },
            "defaults": {
                key: value
                for key, value in cls.__dict__.items()
                if not key.startswith('__') and not callable(value)
            }
        }
    except:
        return 404


waitress.serve(server, host=HOST, port=PORT, threads=THREADS)
Ejemplo n.º 59
0
    Age = final_feature[0][0]
    Sex = final_feature[0][1]
    Class = final_feature[0][2]
    Embarked = final_feature[0][3]
    Age_Class = Age * Class

    final_data = [Class, Sex, Age, Embarked, Age_Class]
    data = np.array(final_data).reshape(-1, 5)

    prediction = model_predict(data)

    result = ['Did not Survive', 'Survived']

    age1 = ['<= 16', '17-32', '33-48', '49-64', '>= 65']
    sex1 = ['Male', 'Female']
    class1 = ['', 'First Class', 'Second Class', 'Third Class']
    embarked1 = ['Southampton', 'Cherbourg', 'Queenstown']

    output1 = age1[Age], sex1[Sex], class1[Class], embarked1[Embarked]
    output2 = result[prediction]

    return render_template('index.html',
                           prediction_text1='Input :  {}'.format(output1),
                           prediction_text2='Result :  {}'.format(output2))


if __name__ == '__main__':
    # app.run(debug=True)
    serve(app, host='0.0.0.0', port=8000)
Ejemplo n.º 60
0
    prev_page = page - 1
    if prev_page < 0:
        prev_page = -1 
    
    return {
        "n_rows" : n_rows,
        "pages" : pages,
        "page" : page,
        "next_page" : next_page,
        "prev_page" : prev_page
    }
def get_db():
    if 'db' not in g:
        g.db = db_layer.DbLayer(DB_PATH, ENTRIES_PER_PAGE)

    return g.db

def close_db(e=None):
    db = g.pop('db', None)
    if db is not None:
        db.close()

if __name__ == "__main__":
    init()

    url_prefix = ''
    if len(sys.argv) > 1:
        url_prefix = sys.argv[1]
    
    waitress.serve(app, host='0.0.0.0', url_prefix=url_prefix, port=8090)