예제 #1
0
    def run(self):
        # FIXME: All files under current directory
        files = ["index.wsgi"]

        # XXX:
        # when django template renders `environ` in its 500 page, it will
        # try to call `environ['werkzeug.server.shutdown'` and cause the
        # server exit unexpectedly.
        # See: https://docs.djangoproject.com/en/dev/ref/templates/api/#variables-and-lookups
        def wrap(app):
            def _(environ, start_response):
                try:
                    del environ["werkzeug.server.shutdown"]
                except KeyError:
                    pass
                return app(environ, start_response)

            return _

        if "WERKZEUG_RUN_MAIN" in os.environ:
            os.environ["sae.run_main"] = "1"

        self.application = _channel_wrapper(self.application)
        from werkzeug.serving import run_simple

        run_simple(
            self.conf.host,
            self.conf.port,
            wrap(self.application),
            use_reloader=True,
            use_debugger=True,
            extra_files=files,
            static_files=self.static_files,
        )
예제 #2
0
def runserver(hostname, port, no_reloader, debugger, no_evalex, threaded, processes):
    """Start a new development server."""
    reloader = not no_reloader
    evalex = not no_evalex
    run_simple(hostname, port, app,
               use_reloader=reloader, use_debugger=debugger,
               use_evalex=evalex, threaded=threaded, processes=processes)
예제 #3
0
파일: cli.py 프로젝트: L-moon/flask
def run_command(info, host, port, reload, debugger, eager_loading,
                with_threads):
    """Runs a local development server for the Flask application."""
    from werkzeug.serving import run_simple
    if reload is None:
        reload = info.debug
    if debugger is None:
        debugger = info.debug
    if eager_loading is None:
        eager_loading = not reload

    app = info.make_wsgi_app(use_eager_loading=eager_loading)

    # Extra startup messages.  This depends a but on Werkzeug internals to
    # not double execute when the reloader kicks in.
    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        # If we have an import path we can print it out now which can help
        # people understand what's being served.  If we do not have an
        # import path because the app was loaded through a callback then
        # we won't print anything.
        if info.app_import_path is not None:
            print(' * Serving Flask app "%s"' % info.app_import_path)
        if info.debug is not None:
            print(' * Forcing debug %s' % (info.debug and 'on' or 'off'))

    run_simple(host, port, app, use_reloader=reload,
               use_debugger=debugger, threaded=with_threads)
예제 #4
0
파일: manage.py 프로젝트: chifeng/uliweb
    def handle(self, options, global_options, *args):
        from werkzeug.serving import run_simple

        if self.develop:
            include_apps = ['plugs.develop']
            app = make_application(options.debug, project_dir=global_options.project, 
                        include_apps=include_apps, settings_file=global_options.settings,
                        local_settings_file=global_options.local_settings)
        else:
            app = make_application(options.debug, project_dir=global_options.project,
                settings_file=global_options.settings,
                local_settings_file=global_options.local_settings)
            include_apps = []
        extra_files = collect_files(global_options.apps_dir, self.get_apps(global_options, include_apps))
        
        if options.ssl:
            ctx = 'adhoc'
            
            default = False
            if not os.path.exists(options.ssl_key):
                log.info(' * SSL key file (%s) not found, will use default ssl config' % options.ssl_key)
                default = True
            if not os.path.exists(options.ssl_cert) and not default:
                log.info(' * SSL cert file (%s) not found, will use default ssl config' % options.ssl_cert)
                default = True
                
            if not default:
                ctx = (options.ssl_key, options.ssl_cert)
        else:
            ctx = None
        run_simple(options.hostname, options.port, app, options.reload, False, True,
                   extra_files, 1, options.thread, options.processes, ssl_context=ctx)
예제 #5
0
	def cmd_runserver(self, listen='8000'):
		from werkzeug.serving import run_simple

		def view_index(request):
			path = os.path.join(STATIC_FILES_DIR, 'index.html')
			return Response(open(path, 'rb'), mimetype='text/html')

		self.view_index = view_index
		self.urls.add(Rule('/', endpoint='index'))

		def view_generated(request, path):
			endpoint = self.generated_files.get(path)
			if endpoint is None:
				raise NotFound
			iterable = getattr(self, 'generate_' + endpoint)()
			mimetype = mimetypes.guess_type(path)[0]
			return Response(iterable, mimetype=mimetype)

		self.view_generated = view_generated
		self.urls.add(Rule('/static/<path:path>', endpoint='generated'))

		if ':' in listen:
			(address, port) = listen.rsplit(':', 1)
		else:
			(address, port) = ('localhost', listen)

		run_simple(address, int(port), app, use_reloader=True, static_files={
			'/static/': STATIC_FILES_DIR,
		})
예제 #6
0
파일: cli.py 프로젝트: AEliu/flask
def run_command(info, host, port, reload, debugger, eager_loading,
                with_threads, cert):
    """Run a local development server.

    This server is for development purposes only. It does not provide
    the stability, security, or performance of production WSGI servers.

    The reloader and debugger are enabled by default if
    FLASK_ENV=development or FLASK_DEBUG=1.
    """
    debug = get_debug_flag()

    if reload is None:
        reload = debug

    if debugger is None:
        debugger = debug

    if eager_loading is None:
        eager_loading = not reload

    show_server_banner(get_env(), debug, info.app_import_path, eager_loading)
    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)

    from werkzeug.serving import run_simple
    run_simple(host, port, app, use_reloader=reload, use_debugger=debugger,
               threaded=with_threads, ssl_context=cert)
예제 #7
0
파일: app.py 프로젝트: cswaroop/erpnext
def serve(port=8000, profile=False):
	global application
	from werkzeug.serving import run_simple
	if profile:
		application = ProfilerMiddleware(application)
	run_simple('0.0.0.0', int(port), application, use_reloader=True, 
		use_debugger=True, use_evalex=True)
예제 #8
0
def main():
    from docopt import docopt
    from werkzeug.serving import run_simple

    arguments = docopt(__doc__)
    app = DapServer(arguments['<config.yaml>'])
    run_simple(arguments['--ip'], int(arguments['--port']), app, use_reloader=True)
예제 #9
0
def main():
    # morepath.autosetup()
    config = morepath.setup()
    config.scan()
    config.commit()
    # morepath.run(App())
    run_simple('localhost', 5000, App(), use_reloader=True)
예제 #10
0
파일: agent.py 프로젝트: kaurikim/octavia
def main():
    # comment out to improve logging
    service.prepare_service(sys.argv)

    # Workaround for an issue with the auto-reload used below in werkzeug
    # Without it multiple health senders get started when werkzeug reloads
    if not os.environ.get('WERKZEUG_RUN_MAIN'):
        health_sender_proc = multiproc.Process(name='HM_sender',
                                               target=health_daemon.run_sender,
                                               args=(HM_SENDER_CMD_QUEUE,))
        health_sender_proc.daemon = True
        health_sender_proc.start()

    # We will only enforce that the client cert is from the good authority
    # todo(german): Watch this space for security improvements
    ctx = OctaviaSSLContext(ssl.PROTOCOL_SSLv23)

    ctx.load_cert_chain(CONF.amphora_agent.agent_server_cert,
                        ca=CONF.amphora_agent.agent_server_ca)

    # This will trigger a reload if any files change and
    # in particular the certificate file
    serving.run_simple(hostname=CONF.haproxy_amphora.bind_host,
                       port=CONF.haproxy_amphora.bind_port,
                       application=server.app,
                       use_debugger=CONF.debug,
                       ssl_context=ctx,
                       use_reloader=True,
                       extra_files=[CONF.amphora_agent.agent_server_cert])
예제 #11
0
파일: manage.py 프로젝트: zhaiwei/project
def runserver(host='localhost', port=5000):
    from werkzeug.serving import run_simple
    from bbs.orm import connect_db
    from bbs import app

    connect_db()
    run_simple(host, int(port), app, use_reloader=True, use_debugger=True)
예제 #12
0
파일: app.py 프로젝트: aboganas/frappe
def serve(port=8000, profile=False, site=None, sites_path='.'):
	global application, _site, _sites_path
	_site = site
	_sites_path = sites_path

	from werkzeug.serving import run_simple

	if profile:
		application = ProfilerMiddleware(application, sort_by=('cumtime', 'calls'))

	if not os.environ.get('NO_STATICS'):
		application = SharedDataMiddleware(application, {
			b'/assets': os.path.join(sites_path, 'assets').encode("utf-8"),
		})

		application = StaticDataMiddleware(application, {
			b'/files': os.path.abspath(sites_path).encode("utf-8")
		})

	application.debug = True
	application.config = {
		'SERVER_NAME': 'localhost:8000'
	}

	run_simple('0.0.0.0', int(port), application, use_reloader=True,
		use_debugger=True, use_evalex=True, threaded=True)
예제 #13
0
def main(options):
    app_root = os.getcwd()

    conf_path = os.path.join(app_root, 'config.yaml')
    conf = yaml.load(open(conf_path, "r"))

    # if env `WERKZEUG_RUN_MAIN` is not defined, then we are in 
    # the reloader process.
    if os.environ.get('WERKZEUG_RUN_MAIN', False):
        setup_sae_environ(conf, options)

        try:
            index = imp.load_source('index', 'index.wsgi')
        except IOError:
            print "Seems you don't have an index.wsgi"
            return

        if not hasattr(index, 'application'):
            print "application not found in index.wsgi"
            return

        if not callable(index.application):
            print "application is not a callable"
            return

        application = index.application
    else:
        application = 1

    statics = {}
    if conf.has_key('handlers'):
        for h in conf['handlers']:
            url = h['url']
            if h.has_key('static_dir'):
                statics[url] = os.path.join(app_root, h['static_dir'])
            elif h.has_key('static_path'):
                statics[url] = os.path.join(app_root, h['static_path'])

    if not len(statics):
        statics.update({
            '/static': os.path.join(app_root,  'static'),
            '/media': os.path.join(app_root,  'media'),
            '/favicon.ico': os.path.join(app_root,  'favicon.ico'),
        })

    if options.storage:
        # stor dispatch: for test usage only
        statics['/stor-stub'] = os.path.abspath(options.storage)

    # FIXME: All files under current directory
    files = ['index.wsgi']

    try:
        run_simple(options.host, options.port, application,
                    use_reloader = True,
                    use_debugger = True,
                    extra_files = files,
                    static_files = statics, threaded=True)
    except KeyboardInterrupt:
        pass
예제 #14
0
파일: api.py 프로젝트: charliekang/magnum
def main():
    service.prepare_service(sys.argv)

    gmr.TextGuruMeditation.setup_autorun(version)

    # Enable object backporting via the conductor
    base.MagnumObject.indirection_api = base.MagnumObjectIndirectionAPI()

    app = api_app.load_app()

    # Setup OSprofiler for WSGI service
    profiler.setup('magnum-api', CONF.host)

    # SSL configuration
    use_ssl = CONF.api.enabled_ssl

    # Create the WSGI server and start it
    host, port = CONF.api.host, CONF.api.port

    LOG.info(_LI('Starting server in PID %s'), os.getpid())
    LOG.debug("Configuration:")
    CONF.log_opt_values(LOG, logging.DEBUG)

    LOG.info(_LI('Serving on %(proto)s://%(host)s:%(port)s'),
             dict(proto="https" if use_ssl else "http", host=host, port=port))

    workers = CONF.api.workers
    if not workers:
        workers = processutils.get_worker_count()
    LOG.info(_LI('Server will handle each request in a new process up to'
                 ' %s concurrent processes'), workers)
    serving.run_simple(host, port, app, processes=workers,
                       ssl_context=_get_ssl_configs(use_ssl))
예제 #15
0
def main():
    """ Runs the Flux Flask application and all required components. """

    # Test if Git version is at least 2.3 (for GIT_SSH_COMMAND)
    git_version = subprocess.check_output(["git", "--version"]).decode().strip()
    if git_version < "git version 2.3":
        print("Error: {!r} installed but need at least 2.3".format(git_version))
        sys.exit(1)

    # Make sure the root user exists and has all privileges.
    with models.Session() as session:
        models.User.create_root_if_not_exists(session)

    # Create a dispatcher for the sub-url under which the app is run.
    url_prefix = urlparse(config.app_url).path
    if url_prefix and url_prefix != "/":
        print(url_prefix)
        from werkzeug.wsgi import DispatcherMiddleware

        target_app = DispatcherMiddleware(flask.Flask("_dummy_app"), {url_prefix: app})
    else:
        target_app = app

    print(" * starting builder threads...")
    build.run_consumers(num_threads=config.parallel_builds)
    build.update_queue()
    try:
        from werkzeug.serving import run_simple

        run_simple(config.host, config.port, target_app, use_reloader=False)
    finally:
        print(" * stopping builder threads...")
        build.stop_consumers()
예제 #16
0
파일: app_eventlet.py 프로젝트: jonahwu/lab
def build_server():
    print 'start to build paste server'


    eventlet.hubs.use_hub('poll')
    eventlet.patcher.monkey_patch(all=False, socket=True)


    app = load_app()
    # Create the WSGI server and start it
    #host, port = cfg.CONF.api.host, cfg.CONF.api.port
    host = '0.0.0.0'
    port = '8080'

    #LOG.info(_('Starting server in PID %s') % os.getpid())
    #LOG.info(_("Configuration:"))
    #cfg.CONF.log_opt_values(LOG, logging.INFO)

    if host == '0.0.0.0':
        #LOG.info(_(
        #    'serving on 0.0.0.0:%(sport)s, view at http://127.0.0.1:%(vport)s')
        #    % ({'sport': port, 'vport': port}))
        print 'port %s'%port
    else:
        #LOG.info(_("serving on http://%(host)s:%(port)s") % (
        #         {'host': host, 'port': port}))
        print 'host %s'%host

    #workers = service.get_workers('api')
    workers =1
    #serving.run_simple(host, port,
    #                  app, processes=workers, threaded=1)
    serving.run_simple(host, port,
                      app, processes=workers)
    """
예제 #17
0
    def _runweb():
        """Запускаем прием писем по HTTP"""

        try:
            run_simple("0.0.0.0", SRV_PORT, wcgiapp)
        except Exception as e:
            log.error("HTTP service stopped with message: %s" % e)
예제 #18
0
파일: app.py 프로젝트: vhrspvl/vhrs-frappe
def serve(port=8000, profile=False, site=None, sites_path='.'):
	global application, _site, _sites_path
	_site = site
	_sites_path = sites_path

	from werkzeug.serving import run_simple

	if profile:
		application = ProfilerMiddleware(application, sort_by=('cumtime', 'calls'))

	if not os.environ.get('NO_STATICS'):
		application = SharedDataMiddleware(application, {
			'/assets': os.path.join(sites_path, 'assets'),
		})

		application = StaticDataMiddleware(application, {
			'/files': os.path.abspath(sites_path)
		})

	application.debug = True
	application.config = {
		'SERVER_NAME': 'localhost:8000'
	}

	in_test_env = os.environ.get('CI')
	if in_test_env:
		log = logging.getLogger('werkzeug')
		log.setLevel(logging.ERROR)

	run_simple('0.0.0.0', int(port), application,
		use_reloader=not in_test_env,
		use_debugger=not in_test_env,
		use_evalex=not in_test_env,
		threaded=True)
예제 #19
0
def _dev_server():
    _patch_reloader_loop()
    sys.path.insert(0, sys.argv[1])
    import testsuite_app

    app = _get_pid_middleware(testsuite_app.app)
    serving.run_simple(application=app, **testsuite_app.kwargs)
예제 #20
0
파일: manage.py 프로젝트: jamiesun/uliweb
    def handle(self, options, global_options, *args):
        from werkzeug.serving import run_simple

        if self.develop:
            include_apps = ['plugs.develop']
            app = make_application(options.debug, project_dir=global_options.project, 
                        include_apps=include_apps, settings_file=global_options.settings,
                        local_settings_file=global_options.local_settings)
        else:
            app = make_application(options.debug, project_dir=global_options.project,
                settings_file=global_options.settings,
                local_settings_file=global_options.local_settings)
            include_apps = []
        extra_files = collect_files(global_options.apps_dir, self.get_apps(global_options, include_apps))
        
        if options.ssl:
            from OpenSSL import SSL
            ctx = SSL.Context(SSL.SSLv23_METHOD)
            if not os.path.exists(options.ssl_key):
                log.error("Can't find ssl key file [%s], please check it first." % options.ssl_key)
                sys.exit(1)
            if not os.path.exists(options.ssl_cert):
                log.error("Can't find ssl certificate file [%s], please check it first." % options.ssl_key)
                sys.exit(1)
            ctx.use_privatekey_file(options.ssl_key)
            ctx.use_certificate_file(options.ssl_cert)
        else:
            ctx = None
        run_simple(options.hostname, options.port, app, options.reload, False, True,
                   extra_files, 1, options.thread, options.processes, ssl_context=ctx)
예제 #21
0
    def run(self):
        t = start_daemon_thread(self.server.serve_forever)
        logger.info("Manager running in thread: %s", t.name)

        run_simple(self.config['MANAGER_HOST'],
                   self.config['MANAGER_HTTP_PORT'],
                   self, threaded=True, use_debugger=True)
예제 #22
0
def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser()

    # Keep this for backwards compat
    parser.add_argument(
        "service",
        type=str,
        nargs='?',  # http://stackoverflow.com/a/4480202/731592
        default=None)
    parser.add_argument(
        '-H', '--host', type=str,
        help='Which host to bind',
        default='0.0.0.0')
    parser.add_argument(
        '-p', '--port', type=int,
        help='Port number to use for connection',
        default=5000)

    args = parser.parse_args(argv)

    # Wrap the main application
    main_app = DomainDispatcherApplication(create_backend_app, service=args.service)
    main_app.debug = True

    run_simple(args.host, args.port, main_app, threaded=True)
예제 #23
0
def main(argv, options, p):
    if not options.plist:
        if not have_biplist:
            print >>sys.stderr, "Note: biplist module not available therefore plists can only transferred in XML format."

        use_reloader = options.reloader
        if use_reloader:
            try:
                from werkzeug.serving import run_simple
            except ImportError:
                print >>sys.stderr, "Warning: Cannot use auto-reloading because the werkzeug module is not available"
                use_reloader = False

        # We start Watcher before any server so all servers run in the same process for shared access to the globals.
        if not use_reloader:
            Watcher()

        if not use_reloader or os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
            print "Starting OSCServer on UDP port %s" % OSC_LISTENER_PORT
            startOSCServer()

        print "Starting RLOserver on TCP port %s" % RLO_LISTENER_PORT
        if not use_reloader:
            serv = make_server('', RLO_LISTENER_PORT, wsgiref.validate.validator(my_app))
            serv.serve_forever()
        else:
            run_simple('', RLO_LISTENER_PORT, my_app, use_reloader=True)
    else:
        if not options.project:
            p.error("please specify the project")
        data = rloconfigAsXML(options.project)
        print data,
예제 #24
0
    def cmd_runserver(self, listen='8000'):
        from werkzeug.serving import run_simple

        def view_index(request):
            path = os.path.join(STATIC_FILES_DIR, 'index.html')
            return Response(open(path, 'rb'), mimetype='text/html')

        self.view_index = view_index
        self.urls.add(Rule('/', endpoint='index'))

        def view_generated(request, path):
            for filename, func, _ in self.get_generated_files():
                if path == filename:
                    mimetype = mimetypes.guess_type(path)[0]
                    return Response(func(), mimetype=mimetype)
            raise NotFound

        self.view_generated = view_generated
        self.urls.add(Rule('/static/<path:path>', endpoint='generated'))
        self.urls.add(Rule('/<any("serviceworker.js"):path>', endpoint='generated'))

        if ':' in listen:
            (address, port) = listen.rsplit(':', 1)
        else:
            (address, port) = ('localhost', listen)

        run_simple(address, int(port), app, use_reloader=True, static_files={
            '/static/': STATIC_FILES_DIR,
        })
예제 #25
0
파일: manage.py 프로젝트: zhaiwei/project
    def run(self, host, port):
        from werkzeug.serving import run_simple
        from bbs import app
        from bbs.orm import connect_db

        connect_db()
        run_simple(host, int(port), app, use_reloader=True, use_debugger=True)
예제 #26
0
파일: dev_server.py 프로젝트: meliu/thunder
def main(app_root, options):

    try:
        index = imp.load_source('index', 'index.wsgi')
    except IOError:
        print "Seems you don't have an index.wsgi"
        sys.exit(-1)

    if not hasattr(index, 'application'):
        print "application not found in index.wsgi"
        sys.exit(-1)

    if not callable(index.application):
        print "application is not a callable"
        sys.exit(-1)

    statics = { '/static': os.path.join(app_root,  'static'),
              '/media': os.path.join(app_root,  'media'),
             '/favicon.ico': os.path.join(app_root,  'favicon.ico'),
             }

    # FIXME: All files under current directory
    files = ['index.wsgi']

    try:
        run_simple('localhost', options.port, index.application,
                    use_reloader = True,
                    use_debugger = True,
                    extra_files = files,
                    static_files = statics)

    except KeyboardInterrupt:
        print "OK"
예제 #27
0
 def serverThread(self):
     if self.threads > 1:
         run_simple(
             "localhost", self.port, self.serveApplication, threaded=True, processes=self.threads, use_debugger=False
         )
     else:
         run_simple("localhost", self.port, self.serveApplication, use_debugger=False)
예제 #28
0
 def callJSONRPCServer(self,bmcPluginName):
     bmcUtil = Util()
     bmcUtil.setValue(bmcPluginName)
     bmcHostName = bmcUtil.readLocalAppVariableFile("BMC_JSONRPCCALL_HOST_NAME")
     bmcPortNumber = bmcUtil.readLocalAppVariableFile("BMC_JSON_RPCCALL_PORT_NUMBER")
     #Running
     run_simple(bmcUtil.removeDoubleQuotas(bmcHostName), bmcPortNumber, self.application)
예제 #29
0
파일: http.py 프로젝트: rickmak/py-skygear
 def run(self):
     """
     Start the web server.
     """
     run_simple(self.hostname, self.port, self.dispatch,
                threaded=True,
                use_reloader=self.debug)
예제 #30
0
파일: interface.py 프로젝트: wxdublin/rules
 def run(self):
     self._host.run()
     if self._port != 443:
         run_simple(self._host_name, self._port, self, threaded=True)
     else:
         make_ssl_devcert('key', host=self._host_name)
         run_simple(self._host_name, self._port, self, threaded=True, ssl_context=('key.crt', 'key.key'))
예제 #31
0
from flask_migrate import Migrate
from configs.config import config_dict
import os
import sys
from app import create_app, db
from werkzeug.serving import run_simple
from flaskext.markdown import Markdown

import logging
get_config_mode = os.environ.get('GENTELELLA_CONFIG_MODE', 'Debug')

try:
    config_mode = config_dict[get_config_mode.capitalize()]
except KeyError:
    sys.exit(
        'Error: Invalid GENTELELLA_CONFIG_MODE environment variable entry.')

app = create_app(config_mode)
Markdown(app)
#Migrate(app, db)

if __name__ == "__main__":
    run_simple('localhost',
               5000,
               app,
               use_reloader=True,
               use_debugger=True,
               use_evalex=True)
    #app.run(debug=True)
예제 #32
0
from app import app

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('127.0.0.1', 5000, app, use_debugger=True, use_reloader=True)
# app.run(debug=True, use_reloader=True)
예제 #33
0
    # Populate global settings
    DATA_DIR = settings.get('DataDir')
    BLOCKCHAIN_ENDPOINT = settings.get('DecentralisationProvider')
    DEFAULT_BIND_ADDR = settings.get('DefaultBindAddress')
    DEFAULT_PORT = settings.getint('DefaultPort')

    PRIVATE_ID = keys.get('PrivateKey')
    PUBLIC_ID = keys.get('PublicKey')

    # Parse arguments
    parser = argparse.ArgumentParser(
        description='JSON-RPC daemon for the LambdaCoin blockchain.')
    parser.add_argument('-b',
                        '--bind',
                        default=DEFAULT_BIND_ADDR,
                        help='bind on address')
    parser.add_argument('-p',
                        '--port',
                        default=DEFAULT_PORT,
                        help='listen on port')

    args = parser.parse_args()
    try:
        args.port = int(args.port)
    except ValueError:
        parser.error('Port must be an integer.')

    updater = update()
    run_simple(args.bind, args.port, application)
예제 #34
0
    return _hash, seed, target, height


@dispatcher.add_method
def eth_submitWork(*args):
    global current_block
    print("submitWork")
    current_block += 1
    return True


@dispatcher.add_method
def eth_getBlockByNumber(*args):
    print("gbbn")
    return {
        'number': "0x" + current_block.to_bytes(8, "big").hex(),
        'difficulty': "0x" + difft.to_bytes(8, "big").hex().upper()
    }


@Request.application
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["echo"] = lambda s: s
    dispatcher["add"] = lambda a, b: a + b
    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    return Response(response.json, mimetype='application/json')


run_simple('localhost', 4000, application)
예제 #35
0
from werkzeug.wrappers import Request, Response
from threading import Thread
import subprocess
import time

class DeployWorker(Thread):
  def __init__(self):
    Thread.__init__(self)
    self.deploy = False

  def run(self):
    while True:
      if self.deploy:
        self.deploy = False
        subprocess.call(["/bin/bash", "/root/LegacyPlayersV3/Deploy/deploy.sh"])
      else:
        time.sleep(1)


globalThread = 0
@Request.application
def application(request):
    globalThread.deploy = True
    return Response("Ok!")

if __name__ == "__main__":
    globalThread = DeployWorker()
    globalThread.start()
    from werkzeug.serving import run_simple
    run_simple("0.0.0.0", 5000, application)
예제 #36
0
def run_cmd(info, host, port, url, ssl, ssl_key, ssl_cert, quiet, proxy,
            enable_evalex, evalex_from, reloader_type):
    if port is None:
        port = 8443 if ssl else 8000

    if not enable_evalex:
        evalex_whitelist = False
    elif evalex_from:
        evalex_whitelist = evalex_from
    else:
        evalex_whitelist = True

    if not ssl:
        ssl_ctx = None
    elif ssl_key and ssl_cert:
        ssl_ctx = (ssl_cert, ssl_key)
    else:
        ssl_ctx = 'adhoc'

    if not url:
        proto = 'https' if ssl else 'http'
        url_host = '[{}]'.format(host) if ':' in host else host
        if (port == 80 and not ssl) or (port == 443 and ssl):
            url = '{}://{}'.format(proto, url_host)
        else:
            url = '{}://{}:{}'.format(proto, url_host, port)

    os.environ.pop('FLASK_DEBUG', None)
    os.environ['INDICO_CONF_OVERRIDE'] = repr({
        'BASE_URL': url,
    })

    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        print ' * Serving Indico on {}'.format(url)
        if evalex_whitelist:
            print ' * Werkzeug debugger console on {}/console'.format(url)
            if evalex_whitelist is True:  # noqa
                print ' * Werkzeug debugger console is available to all clients!'

    try:
        from indico.core.config import get_config_path
        extra_files = [get_config_path()]
    except Exception:
        extra_files = None

    # our own logger initialization code runs earlier so werkzeug
    # doesn't initialize its logger
    import logging
    werkzeug_logger = logging.getLogger('werkzeug')
    werkzeug_logger.propagate = False
    werkzeug_logger.setLevel(logging.INFO)
    werkzeug_logger.addHandler(logging.StreamHandler())

    app = _make_wsgi_app(info, url, evalex_whitelist, proxy)
    run_simple(host,
               port,
               app,
               reloader_type=reloader_type,
               use_reloader=(reloader_type != 'none'),
               use_debugger=False,
               use_evalex=False,
               threaded=True,
               ssl_context=ssl_ctx,
               extra_files=extra_files,
               request_handler=QuietWSGIRequestHandler if quiet else None)
예제 #37
0
                      help="the IP address to listen on")
    parser.add_option("-p",
                      "--port",
                      dest="port",
                      type="int",
                      default=8080,
                      help="the port number to listen on")
    parser.add_option(
        '--include-path',
        dest='include',
        help=
        "Add the following colon-separated list of paths to Python's include path (aka sys.path)"
    )
    (options, args) = parser.parse_args()

    if options.include:
        for p in options.include.split(':'):
            sys.path.insert(0, p)

    from werkzeug.serving import run_simple
    import TileStache

    if not os.path.exists(options.file):
        print(
            "Config file not found. Use -c to pick a tilestache config file.",
            file=sys.stderr)
        sys.exit(1)

    app = TileStache.WSGITileServer(config=options.file, autoreload=True)
    run_simple(options.ip, options.port, app)
예제 #38
0
파일: manager.py 프로젝트: rsau/grow
def start(pod,
          host=None,
          port=None,
          open_browser=False,
          debug=False,
          preprocess=True,
          update_check=False):
    main_observer, podspec_observer = file_watchers.create_dev_server_observers(
        pod)
    if preprocess:
        thread = threading.Thread(target=pod.preprocess,
                                  kwargs={'build': False})
        thread.setDaemon(True)
        thread.start()
    port = 8080 if port is None else int(port)
    host = 'localhost' if host is None else host
    patch_broken_pipe_error()
    # Not safe for multi-pod serving env.
    CallbackHTTPServer.pod = pod
    CallbackHTTPServer.open_browser = open_browser
    CallbackHTTPServer.update_check = update_check
    serving.ThreadedWSGIServer = CallbackHTTPServer
    app = main_lib.create_wsgi_app(pod, host, port, debug=debug)
    serving._log = lambda *args, **kwargs: ''
    handler = main_lib.RequestHandler
    num_tries = 0
    done = False

    while num_tries < NUM_TRIES and not done:
        try:
            app.app.port = port
            serving.run_simple(host,
                               port,
                               app,
                               request_handler=handler,
                               threaded=True)
            done = True
        except socket.error as e:
            # if any(x in str(e) for x in ('Errno 48', 'Errno 98')):
            if 'Errno 48' in str(e):
                num_tries += 1
                port += 1
            else:
                # Clean up the file watchers.
                main_observer.stop()
                podspec_observer.stop()

                raise e
        finally:
            if done:
                # Clean up the file watchers.
                main_observer.stop()
                podspec_observer.stop()

                # Ensure ctrl+c works no matter what.
                # https://github.com/grow/grow/issues/149
                os._exit(0)

    text = 'Unable to find a port for the server (tried {}).'
    pod.logger.error(text.format(port))
    sys.exit(-1)
예제 #39
0
 def run(self):
     run_simple('127.0.0.1', 5000, self, threaded=True)
예제 #40
0
def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser()

    # Keep this for backwards compat
    parser.add_argument(
        "service",
        type=str,
        nargs="?",  # http://stackoverflow.com/a/4480202/731592
        default=os.environ.get("MOTO_SERVICE"),
    )
    parser.add_argument("-H",
                        "--host",
                        type=str,
                        help="Which host to bind",
                        default="127.0.0.1")
    parser.add_argument("-p",
                        "--port",
                        type=int,
                        help="Port number to use for connection",
                        default=5000)
    parser.add_argument(
        "-r",
        "--reload",
        action="store_true",
        help="Reload server on a file change",
        default=False,
    )
    parser.add_argument(
        "-s",
        "--ssl",
        action="store_true",
        help=
        "Enable SSL encrypted connection with auto-generated certificate (use https://... URL)",
        default=False,
    )
    parser.add_argument("-c",
                        "--ssl-cert",
                        type=str,
                        help="Path to SSL certificate",
                        default=None)
    parser.add_argument("-k",
                        "--ssl-key",
                        type=str,
                        help="Path to SSL private key",
                        default=None)

    args = parser.parse_args(argv)

    try:
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
    except Exception:
        pass  # ignore "ValueError: signal only works in main thread"

    # Wrap the main application
    main_app = DomainDispatcherApplication(create_backend_app,
                                           service=args.service)
    main_app.debug = True

    ssl_context = None
    if args.ssl_key and args.ssl_cert:
        ssl_context = (args.ssl_cert, args.ssl_key)
    elif args.ssl:
        ssl_context = "adhoc"

    run_simple(
        args.host,
        args.port,
        main_app,
        threaded=True,
        use_reloader=args.reload,
        ssl_context=ssl_context,
    )
예제 #41
0
 def run(self, port=5000, ip='', debug=False):
     run_simple(ip, port, self, use_debugger=debug, use_reloader=True)
예제 #42
0
파일: app.py 프로젝트: zyhndesign/djk
import os
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.contrib.fixers import ProxyFix
from web_app import frontend

frontend_app = frontend.create_app()

application = ProxyFix(DispatcherMiddleware(None, {
    '/app': frontend_app,
}))

if __name__ == "__main__":
    run_simple("0.0.0.0", 7200, application)
예제 #43
0
        self.users = users
        self.realm = realm

    def check_auth(self, username, password):
        return username in self.users and self.users[username] == password

    def auth_required(self, request):
        return Response(
            "Could not verify your access level for that URL.\n"
            "You have to login with proper credentials",
            401,
            {"WWW-Authenticate": 'Basic realm="%s"' % self.realm},
        )

    def dispatch_request(self, request):
        return Response("Logged in as %s" % request.authorization.username)

    def __call__(self, environ, start_response):
        request = Request(environ)
        auth = request.authorization
        if not auth or not self.check_auth(auth.username, auth.password):
            response = self.auth_required(request)
        else:
            response = self.dispatch_request(request)
        return response(environ, start_response)


if __name__ == "__main__":
    application = Application({"user1": "password", "user2": "password"})
    run_simple("localhost", 5000, application)
예제 #44
0
    dispatcher["heart_beat"] = heart_beat
    dispatcher["check_xmode_ontology"] = check_xmode_ontology
    dispatcher["check_xmode_sigsvr"] = check_xmode_sigsvr
    dispatcher["check_xmode_tools"] = check_xmode_tools
    dispatcher["get_version_ontology"] = get_version_ontology
    dispatcher["get_version_wallet"] = get_version_wallet
    dispatcher["get_version_onto_config"] = get_version_onto_config
    dispatcher["get_version_test_config"] = get_version_test_config
    dispatcher["get_version_sigsvr"] = get_version_sigsvr
    dispatcher["get_version_abi"] = get_version_abi
    dispatcher["get_version_test_service"] = get_version_test_service
    dispatcher["stop_test_service"] = stop_test_service

    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    print(request)
    responseobj = json.loads(response.json)
    print(responseobj)
    if "error" not in responseobj:
        responseobj["error"] = 0
    else:
        if "message" in responseobj["error"]:
            responseobj["desc"] = responseobj["error"]["message"]
        if "code" in responseobj["error"]:
            responseobj["error"] = responseobj["error"]["code"]
    print(json.dumps(responseobj))
    return Response(json.dumps(responseobj), mimetype='application/json')


if __name__ == '__main__':
    run_simple(get_host_ip(), config.PORT, application)
예제 #45
0
        help=
        'generates xml metadata metadata.conf in your current directory (does not start server)',
        action="store_true")
    args = p.parse_args()

    # parse config file
    c = get_config(args.config)  # args.config

    if args.createmetadata:
        createSchemaMetadata(c)
        sys.exit()

    # generate and load metadata
    doc = load_metadata(c)

    # start server
    app = configure_app(c, doc)
    app = prepareHTTPProxy(app)
    app = local_manager.make_middleware(app)

    if c.getboolean('authentication', 'required'):
        auth_config = c._sections["authentication"]
        app = Auth(app, auth_config)

    from werkzeug.serving import run_simple
    listen_interface = c.get('server', 'server_listen_interface')
    listen_port = int(c.get('server', 'server_listen_port'))
    logger.info("Starting HTTP server on: interface: %s, port: %i..." %
                (listen_interface, listen_port))
    run_simple(listen_interface, listen_port, application=app)
예제 #46
0
        self.redis.incr('click-count:' + short_id)
        return redirect(link_target)

    def on_short_link_details(self, request, short_id):
        link_target = self.redis.get('url-target:' + short_id)
        if link_target is None:
            raise NotFound()
        click_count = int(self.redis.get('click-count:' + short_id) or 0)
        return self.render_template('short_link_details.html',
                                    link_target=link_target,
                                    short_id=short_id,
                                    click_count=click_count)


def create_app(redis_host='localhost', redis_port=6379, with_static=True):
    app = Shortly({
        'redis_host': redis_host,
        'redis_port': redis_port,
    })
    if with_static:
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app,
            {'static': os.path.join(os.path.dirname(__file__), 'static')})
    return app


if __name__ == '__main__':
    from werkzeug.serving import run_simple
    app = create_app()
    run_simple('0.0.0.0', 8000, app, use_debugger=True, use_reloader=True)
예제 #47
0
# Content Tracker is distributed in the hope that it will be useful,
# 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 Contact Tracker. If not, see <https://www.gnu.org/licenses/>.
#

#import logging
#logging.basicConfig(level=logging.DEBUG)

# If running under Apache mod-wsgi, we have to add the app directory to the
# Python search path.
if __name__.startswith("_mod_wsgi_"):
    import os, sys
    sys.path.insert(0, os.path.dirname(__file__))

# Import the Flask app
from app import app

# If running standalone (not under Apache mod-wsgi), create a web server using
# Werkzeug and connect it to the Flask app imported above. This applies when
# Contact Tracker is run in a Docker container with a reverse proxy such as
# Nginx in front of it providing HTTPS encryption.
if __name__ == "__main__":
    from werkzeug.serving import run_simple
    from werkzeug.middleware.proxy_fix import ProxyFix
    app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_for=1)
    run_simple('0.0.0.0', 5000, app, threaded=True)
예제 #48
0
파일: __init__.py 프로젝트: wholmgren/pydap
            return (np.asarray(source[self.path][key]).astype(
                self.dtype).reshape(self._reshape))

    def reshape(self, *args):
        if len(args) > 1:
            self._reshape = args
        else:
            self._reshape = args
        return self

    @property
    def shape(self):
        return self._shape

    def __len__(self):
        if not self.shape:
            raise TypeError('len() of unsized object')
        else:
            return self.shape[0]

    def _getdims(self):
        return self.dimensions


if __name__ == "__main__":
    import sys
    from werkzeug.serving import run_simple

    application = NetCDFHandler(sys.argv[1])
    run_simple('localhost', 8001, application, use_reloader=True)
예제 #49
0
#!/usr/bin/env python

import os
from reload_app.app import make_app_from_environ

port = int(os.environ.get('PORT', 8000))

from werkzeug.serving import run_simple
run_simple(
    '127.0.0.1',
    port,
    make_app_from_environ(),
    use_debugger=True,
    use_reloader=True,
    static_files={'/client': 'client'},
)
예제 #50
0
import os

from werkzeug.serving import run_simple

from config.wsgi import application

PISMA_HOST = os.getenv("PISMA_HOST", "::")
PISMA_PORT = int(os.getenv("PISMA_PORT", "8000"))

if __name__ == "__main__":
    run_simple(PISMA_HOST, PISMA_PORT, application)
예제 #51
0
        'wsgi_env': '\n'.join(wsgi_env),
        'sys_path': '\n'.join(sys_path)
    }).encode('utf-8')


def test_app(environ, start_response):
    """Simple test application that dumps the environment.  You can use
    it to check if Werkzeug is working properly:

    .. sourcecode:: pycon

        >>> from werkzeug.serving import run_simple
        >>> from werkzeug.testapp import test_app
        >>> run_simple('localhost', 3000, test_app)
         * Running on http://localhost:3000/

    The application displays important information from the WSGI environment,
    the Python interpreter and the installed libraries.
    """
    req = Request(environ, populate_request=False)
    if req.args.get('resource') == 'logo':
        response = logo
    else:
        response = Response(render_testapp(req), mimetype='text/html')
    return response(environ, start_response)


if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 5000, test_app, use_reloader=True)
예제 #52
0
from flask import Flask, request
from flask_restful import Resource, Api
from werkzeug import serving

app = Flask(__name__)
api = Api(app)


class TestApi(Resource):
    def post(self):
        # request_data = request.get_json()
        request_data = request.get_data()
        response_body = request_data
        response_header = {"Content-Type": "application/octet-stream"}
        status_code = 200

        response = app.make_response(
            (response_body, status_code, response_header))

        return response


api.add_resource(TestApi, "/")

if __name__ == "__main__":
    serving.run_simple("0.0.0.0", 5000, app)
예제 #53
0
        request = Request(environ)
        response = self.dispatch_request(request)
        return response(environ, start_response)
    """

    @Request.application
    def wsgi_app(self, request):
        return self.dispatch_request(request)

    def __call__(self, environ, start_response):
        return self.wsgi_app(environ, start_response)


def create_app(redis_host='localhost', redis_port=6379, with_static=True):
    app = Shortly({'redis_host': redis_host, 'redis_port': redis_port})
    if with_static:
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app,
            {'/static': os.path.join(os.path.dirname(__file__), 'static')})
    return app


if __name__ == '__main__':
    from werkzeug.serving import run_simple
    app = create_app()
    run_simple('0.0.0.0',
               6009,
               app.wsgi_app,
               use_debugger=True,
               use_reloader=True)
예제 #54
0
def run_server(
    bindaddr,
    env,
    output_path,
    prune=True,
    verbosity=0,
    lektor_dev=False,
    ui_lang="en",
    browse=False,
    extra_flags=None,
):
    """This runs a server but also spawns a background process.  It's
    not safe to call this more than once per python process!
    """
    wz_as_main = os.environ.get("WERKZEUG_RUN_MAIN") == "true"
    in_main_process = not lektor_dev or wz_as_main
    extra_flags = process_extra_flags(extra_flags)

    if in_main_process:
        background_builder = BackgroundBuilder(
            env,
            output_path=output_path,
            prune=prune,
            verbosity=verbosity,
            extra_flags=extra_flags,
        )
        background_builder.setDaemon(True)
        background_builder.start()
        env.plugin_controller.emit("server-spawn",
                                   bindaddr=bindaddr,
                                   extra_flags=extra_flags)

    app = WebAdmin(
        env,
        output_path=output_path,
        verbosity=verbosity,
        debug=lektor_dev,
        ui_lang=ui_lang,
        extra_flags=extra_flags,
    )

    dt = None
    if lektor_dev and not wz_as_main:
        dt = DevTools(env)
        dt.start()

    if browse:
        browse_to_address(bindaddr)

    try:
        return run_simple(
            bindaddr[0],
            bindaddr[1],
            app,
            use_debugger=True,
            threaded=True,
            use_reloader=lektor_dev,
            request_handler=not lektor_dev and SilentWSGIRequestHandler
            or WSGIRequestHandler,
        )
    finally:
        if dt is not None:
            dt.stop()
        if in_main_process:
            env.plugin_controller.emit("server-stop")
예제 #55
0
        abort(405)

    h = hmac.new(os.environ['GITHUB_PART_HOOK_HMAC'], request.data, sha1)
    if not rcbuild.debug and not hmac.compare_digest(
            request.headers["X-Hub-Signature"], u"sha1=" + h.hexdigest()):
        abort(403)

    updateBuildSkeletonHelper()
    return 'ok'


@rcbuild.route('/healthz')
def healthz():
    return Response(response="ok",
                    content_type="Content-Type: text/plain; charset=utf-8",
                    status=requests.codes.ok)


updatePartCategoriesHelper()
updateBuildSkeletonHelper()
updatePartIndexHelper()
if __name__ == '__main__':
    application.debug = True
    from werkzeug.serving import run_simple
    run_simple('127.0.0.1',
               5001,
               application,
               use_reloader=True,
               use_debugger=True,
               use_evalex=True)
예제 #56
0
 def action(hostname = ('h', hostname), port = ('p', port), threaded = threaded, processes = processes):
     from werkzeug.serving import run_simple
     app = ProfilerMiddleware(app_factory(), stream, sort_by, restrictions)
     run_simple(hostname, port, app, False, None, threaded, processes)
예제 #57
0
from adsmutils import ADSFlask
from .views import WordCloud
from .views import AuthorNetwork
from .views import PaperNetwork
from flask_restful import Api
from flask_discoverer import Discoverer
from werkzeug.serving import run_simple


def create_app(**config):
    """Application factory"""

    app = ADSFlask(__name__, static_folder=None, local_config=config or {})

    app.url_map.strict_slashes = False

    api = Api(app)

    api.add_resource(WordCloud, '/word-cloud')
    api.add_resource(AuthorNetwork, '/author-network')
    api.add_resource(PaperNetwork, '/paper-network')
    
    discoverer = Discoverer(app)

    return app

if __name__ == "__main__":
    run_simple('0.0.0.0', 5555, create_app(), use_reloader=False, use_debugger=False)

예제 #58
0
from server import *
app = Chocolate()


@app.path("/")
def home(request, response):
    response.text = "Hello World!"


@app.path("/whrose/{name}.py")
def rose(request, response, name=""):
    response.text = "Hello %s!" % name


from werkzeug.serving import run_simple
#run_simple('localhost', 8080, app, debug=True)
#run_simple('localhost', 8080, app, use_reloader=True)
import werkzeug as w
print("Running on Werkzeug " + w.__version__)
run_simple('localhost', 8080, app, use_reloader=True)
예제 #59
0
 def start(self):
     run_simple(self._conf.host,
                self._conf.port,
                self.__create_calls,
                ssl_context=self._conf.ssl_ctx,
                threaded=True)
예제 #60
0
 lambda app: aioserver([
     f'{AIOHTTP_DEV_CLIENT}', '--host', HOST, '--port', PORT,
     '--debug-toolbar' if DEBUG else '--no-debug-toolbar', '--livereload'
     if RELOAD else '--no-livereload'
 ]),
 'bottle':
 lambda app: app.run(host=HOST, port=PORT, debug=DEBUG, reloader=RELOAD),
 'cherrypy':
 lambda app: cherrypy.server.start(),
 'django':
 lambda app: djserver.Command().handle(addrport=f'{HOST}:{PORT}',
                                       use_reloader=RELOAD,
                                       use_threading=True,
                                       use_ipv6=False),
 'falcon':
 lambda app: run_simple(
     HOST, PORT, app, use_debugger=DEBUG, use_reloader=RELOAD),
 'flask':
 lambda app: app.run(HOST, PORT, debug=DEBUG, use_reloader=RELOAD),
 'hypercorn':
 lambda app: run.run_single(app,
                            Config.from_mapping({
                                'host': HOST,
                                'port': PORT,
                                'debug': DEBUG,
                                'use_reloader': RELOAD
                            }),
                            loop=asyncio.get_event_loop()),
 'molten':
 lambda app: run_simple(
     HOST, PORT, app, use_debugger=DEBUG, use_reloader=RELOAD),
 'pulsar':