Example #1
0
def main():
   if __where__ == 'local' :
     from paste import httpserver
     httpserver.serve(app, host='127.0.0.1', port='8080')
     print("App launched.")
   else:
     app.run()
def main():
    desc = """
           The youtube-dl API server.
           """

    parser = argparse.ArgumentParser(description=desc)

    default_port = 9191
    port_help = 'The port the server will use. The default is: {}'
    port_help = port_help.format(default_port)
    parser.add_argument('-p', '--port',
                        default=default_port,
                        type=int,
                        help=port_help
                        )

    parser.add_argument('--version', action='store_true',
                        help='Print the version of the server')

    args = parser.parse_args()
    if args.version:
        print(__version__)
        exit(0)
    
    setup()
    httpserver.serve(app, host='localhost', port=args.port)
Example #3
0
def start():
    """Starts the BespinServer on localhost port 8080 for development.
    
    You can change the port and allow remote connections by setting
    server.port or server.address on the command line.
    
    paver server.address=your.ip.address server.port=8000 start
    
    will allow remote connections (assuming you don't have a firewall
    blocking the connection) and start the server on port 8000.
    """
    # automatically install Dojo if it's not there already
    if not (options.dojo.destination / "dojo").exists():
        dojo()
    
    from bespin import config, controllers
    from paste.httpserver import serve
    
    options.order('server')
    
    config.set_profile('dev')
    
    if options.server.try_build:
        config.c.static_dir = (options.build_dir / "frontend").abspath()
    
    if options.server.dburl:
        config.c.dburl = options.server.dburl
    
    if options.server.async:
        config.c.async_jobs = True
        config.c.queue_path = path.getcwd() / "queue.db"
    
    config.activate_profile()
    port = int(options.port)
    serve(controllers.make_app(), options.address, port, use_threadpool=True)
Example #4
0
 def run(self, handler): # pragma: no cover
     from paste import httpserver
     if not self.quiet:
         from paste.translogger import TransLogger
         handler = TransLogger(handler)
     httpserver.serve(handler, host=self.host, port=str(self.port),
                      **self.options)
Example #5
0
def main():
    import zope.app.wsgi
    zope_conf = os.path.join(here, 'zope.conf')
    zope = zope.app.wsgi.getWSGIApplication(zope_conf)

    from repoze.who.middleware import PluggableAuthenticationMiddleware
    from repoze.who.config import WhoConfig
    parser = WhoConfig(here)
    parser.parse(open(os.path.join(here, 'who.ini')))
    log_stream = sys.stdout
    log_level = logging.DEBUG

    app = PluggableAuthenticationMiddleware(
        zope,
        parser.identifiers,
        parser.authenticators,
        parser.challengers,
        parser.mdproviders,
        parser.request_classifier,
        parser.challenge_decider,
        log_stream,
        log_level,
        )
    from paste import httpserver
    httpserver.serve(app, host='0.0.0.0', port='9876')
Example #6
0
 def start_server(self, host=settings.host, port=settings.port):
     try:
         print "starting at " + host + ":" + port
         httpserver.serve(self.root_app, host, int(port))
     except Exception:
         print "Couldn't start server"
         raise
Example #7
0
def run(app, default_host='localhost', default_port=8080):
    usage = "usage: %prog <servertype> [options]\n"
    usage += "Server types: %s" % (", ".join(SERVERS))
    parser= OptionParser(usage=usage)
    parser.add_option('-H', '--host', dest='host', default=default_host,
        help='Hostname (default: %s)' % (default_host), metavar='HOSTNAME')
    parser.add_option('-p', '--port', dest='port', default=default_port,
        help='Port (default: %s)' % (default_port), metavar='PORT')
    # TODO
    # parser.add_option('-q', '--quiet', dest='quiet', default=False,
        # action="store_true", help='Suppress stdout and stderr')
    (options, args) = parser.parse_args()
    if len(args) != 1 or args[0] not in SERVERS:
        parser.print_usage()
        exit(1)
        
    try:
        port = int(options.port)
    except:
        print "Port must be an integer."
        exit(1)
    
    run_method = args[0]
    if run_method in FLUP_SERVERS:
        module_name = 'flup.server.' + run_method
        __import__(module_name)
        modules[module_name].WSGIServer(app, bindAddress=(options.host, port)).run()
        
    elif run_method == 'http':
        from paste import httpserver
        httpserver.serve(app, host=options.host, port=port, use_threadpool=True)
        
    else:
        parser.print_usage()
        exit(1)
Example #8
0
def main():
    """
    Starts an http server process.
    """
    settings = {
        'reload_all':True,
        'debug_all':True,
        'db':os.path.join(app_root, 'tasks.db'),
        'mako.directories':os.path.join(app_root, 'templates')
    }
    session_factory = UnencryptedCookieSessionFactoryConfig('sekret')
    config = Configurator(
        settings=settings,
        session_factory=session_factory
    )

    # route setup
    config.add_route('list', '/')
    config.add_route('new', '/new')
    config.add_route('close', '/close/{id}')
    config.add_static_view('static', os.path.join(app_root, 'static'))

    # this comes after any other setup?
    config.scan()

    app = config.make_wsgi_app()
    serve(app, host='0.0.0.0')
Example #9
0
def dev_server(
    app=None, host='127.0.0.1', port=8000, logging=True, weberror=True,
    use_threadpool=None, threadpool_workers=10, request_queue_size=5,
    repoze_tm=False, **config):
    """
    Run a development server, hosting the ToscaWidgets application.
    This requires Paste and WebError, which are only sure to be available if
    tw2.devtools is installed.
    """
    config.setdefault('debug', True)
    config.setdefault('controller_prefix', '/')
    app = twc.make_middleware(app, **config)

    if repoze_tm:
        import repoze.tm as rtm, tw2.sqla as tws
        app = rtm.TM(app, tws.commit_veto)

    if weberror:
        import weberror.errormiddleware as we
        app = we.ErrorMiddleware(app, debug=True)

    if logging:
        import paste.translogger as pt
        app = pt.TransLogger(app)

    import paste.httpserver as ph
    ph.serve(app, host=host, port=port,
             use_threadpool=use_threadpool,
             threadpool_workers=threadpool_workers,
             request_queue_size=request_queue_size)
Example #10
0
 def run(self, host=None, port=8080, debug=False):
     self.config.end()
     app = self.config.make_wsgi_app()
     if debug:
         app = EvalException(app)
     app = RegistryManager(app)
     serve(app, host, port)
Example #11
0
def main(argv=None):
    if argv is None:
        import sys

        argv = sys.argv

    parser = optparse.OptionParser(description=__doc__, formatter=HelpFormatter())

    parser.add_option(
        "--list", dest="list_components", action="store_true", default=False, help="List available components"
    )

    options, args = parser.parse_args(argv[1:])

    if args:
        if args[0] == "serve":
            from paste.httpserver import serve
            from wiseguy.app import configurator

            serve(configurator)

    if options.list_components:
        ep_parser = EPParser()
        for component_name, component in ep_parser.get_components():
            print component_name, component
Example #12
0
def main():
	_opts = _init_env()
	del _opts

	_routes = [
		(r'/', 'model_service.service_handler'),
		(r'/web/(.+)', 'serv_web.web_handler'),
		(r'/admin/(.+)', 'model_service.admin_handler'),
		(r'/d/([^/]+)', 'model_service.metedata_handler'),
		(r'/d/([^/]+/\w+/.+)', 'model_service.resource_handler'),
		(r'/m/([^/]+)', 'model_service.model_handler'),
		(r'/s/([^/]+)', 'model_service.status_handler'),
		(r'/o/([^/]+)', 'model_service.output_handler'),
		(r'/data/([^/]+)/([^/]+)', 'model_service.data_cache_handler'),
		(r'/data/([^/]+)', 'model_service.data_cache_handler')
	]

	_config = {}
	_config['webapp2_extras.sessions'] = {
		'secret_key': 'something-very-secret'
	}

	_app = webapp2.WSGIApplication(routes=_routes, debug=True, config=_config)
	_app.error_handlers[400] = handle_error
	_app.error_handlers[404] = handle_error

	from paste import httpserver
	import config
	httpserver.serve(_app, host=config.get_at('general', 'host'), port=config.get_at('general', 'port'))
Example #13
0
def main():
    '''A simple server startup if module is called directly'''
    # port = 8080
    # host = '0.0.0.0'
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("--host", default="0.0.0.0",
                      dest="host",
                      help="host ip to run")
    parser.add_option("-p", "--port",
                      dest="port", default=8080,
                      help="the port to run on.")
    (options, args) = parser.parse_args()
    try:
        import paste
        from paste import httpserver
        # use this for the interactive debugger
        from paste.evalexception import EvalException
        # add the static server component
        from static_serve import static_serve
        my_app = static_serve(app, path='public')
        httpserver.serve(my_app, host=options.host, port=options.port)
        sys.exit(1)
    except ImportError:
        pass

    from wsgiref.simple_server import make_server
    # add the static server component
    from static_serve import static_serve
    my_app = static_serve(app, path='public')
    httpd = make_server(options.host, options.port, my_app)
    print "Serving on port {0}...".format(options.port)
    httpd.serve_forever()
    sys.exit(1)
Example #14
0
 def testGetDb(self):
     db = Database()
     feed = JsonFeed(db)
     
     httpserver.serve(feed.getFeed(), host="localhost", port="8080")
     start_response('200 OK', [('content-type', 'text/x-json')])
     return feed.getFeed()
Example #15
0
def main():
    '''Listen on port 8080 with the demo application.
    '''

    config = Configurator(root_factory=MappingRoot)
    config.registry.settings['sqlalchemy.url'] = \
        'sqlite:////tmp/khufu_sqlalchemy.demo.db'
    config.include('khufu_sqlalchemy')

    config.include('khufu_traversal')
    GroupContainer = config.setup_model_container(Group, [('users', User)])
    UserContainer = config.setup_model_container(User, [('groups', Group)])

    config.add_view(index_view, context=MappingRoot)
    config.add_view(groups_view,
                    context=GroupContainer)
    config.add_view(users_view,
                    context=UserContainer)
    config.add_view(user_view, context=User)
    config.add_view(group_view, context=Group)

    Base.metadata.create_all(bind=config.registry.settings['khufu.dbengine'])
    setup_data(config)
    app = config.make_wsgi_app()
    serve(app, host='0.0.0.0')
Example #16
0
def serve_webapp(webapp, port=None, host=None):
    """Serve the webapp on a recommend port or a free one.

    Return the port the webapp is running one.
    """
    server = None
    if port is not None:
        server = httpserver.serve( webapp, host=host, port=port, start_loop=False )
    else:
        random.seed()
        for i in range( 0, 9 ):
            try:
                port = str( random.randint( 8000, 10000 ) )
                server = httpserver.serve( webapp, host=host, port=port, start_loop=False )
                break
            except socket.error as e:
                if e[0] == 98:
                    continue
                raise
        else:
            raise Exception( "Unable to open a port between %s and %s to start Galaxy server" % ( 8000, 1000 ) )

    t = threading.Thread( target=server.serve_forever )
    t.start()

    return server, port
Example #17
0
def start_server(port):
    if config.SERVER == "lighttpd":
        WSGIServer(control, bindAddress = '/tmp/fcgi.sock').run() 
    elif config.SERVER == "paste":
        httpserver.serve(paste_server_static_wrapper('static', control), port=port)
    else:
        assert False
Example #18
0
def main():
	_opts = _init_env()
	del _opts

	# import serv_web
	# serv_web._zips = serv_web.load_zips()

	_routes = [
		(r'/', 'serv_web.web'),
		(r'/map/(.+)', 'serv_web.map')
	]

	_config = {}
	_config['webapp2_extras.sessions'] = {
		'secret_key': 'something-very-secret'
	}

	import webapp2

	_app = webapp2.WSGIApplication(routes=_routes, debug=True, config=_config)
	_app.error_handlers[400] = handle_error
	_app.error_handlers[404] = handle_error

	from paste import httpserver
	import config
	httpserver.serve(_app, host=config.get_at('general', 'host'), port=config.get_at('general', 'port'))
	print 'done'
Example #19
0
def main():
    pathconfig = sys.argv[1]

    app = webapp2.WSGIApplication([("/lxc/(.*)", APIs)], debug=True, config=readconfig(pathconfig))

    from paste import httpserver

    httpserver.serve(app, host="127.0.0.1", port="8080")
Example #20
0
 def run(self, handler):
     handler = APILogger(handler)
     httpserver.serve(
         handler,
         host=self.host,
         port=str(self.port),
         **self.options
         )
Example #21
0
def main():
    from paste import httpserver
    from paste.urlmap import URLMap
    from paste.urlparser import make_static
    map_app = URLMap()
    map_app['/'] = app
    map_app['/static'] = make_static({}, "static/")
    httpserver.serve(map_app, host='127.0.0.1', port='8080')
Example #22
0
def start_server():
    init_log()
    app = Bottle()
    install_db_plugin(app)
    urls.define_route(app)
    httpserver.serve(app, host=conf.listen_ip, port=conf.listen_port,
                     threadpool_workers=30,
                     request_queue_size=20)
Example #23
0
def run():
    prop_dir = os.path.join(current_dir, '..', 'etc', 'bareon')

    application = deploy.loadapp(
        'config:{prop_dir}/bareon-api-paste.ini'.format(prop_dir=prop_dir),
        name='main',
        relative_to='.')

    httpserver.serve(application, host='127.0.0.1', port='9322')
Example #24
0
def main():
    wsgi_app = loadapp('config:conf.ini', relative_to=dirname(__file__))

    host = '127.0.0.1'
    port = 8080

    #webbrowser.open('http://%s:%d/SimpleApp' % (host, port), new=0)

    serve(wsgi_app, host=host, port=port)
Example #25
0
def _start(root, host=None, port=None, use_simple_log_format=True):
  logging.info('Serving pod with root: {}'.format(root))
  logger_format = ('[%(time)s] "%(REQUEST_METHOD)s %(REQUEST_URI)s" %(status)s'
                   if use_simple_log_format else None)
  root = os.path.abspath(os.path.normpath(root))
  handlers.set_pod_root(root)
  app = main_lib.application
  app = translogger.TransLogger(app, format=logger_format)
  httpserver.serve(app, host=host, port=port)
Example #26
0
def main():
    if not os.path.exists(CONSTANTS.DB_NAME):
        bootstrap.bootstrap()

    from paste import httpserver
    logging.basicConfig(level=logging.INFO)
    logging.info("Event manager started")
    webbrowser.open("http://127.0.0.1:8080")
    httpserver.serve(web_app, host='127.0.0.1', port='8080')
    logging.info("Event manager terminated")
Example #27
0
    def __init__(self, port):
        self.__port = port
        routes = [
		    ('/test', TestHandler),
                    (r'/.*', GeneralHandler)
                 ]
        static_app = StaticURLParser(root_dir)
        web_app = WSGIApplication(routes, debug=True)
        self.__app = Cascade([static_app, web_app])
        httpserver.serve(self.__app, host='', port=port)
Example #28
0
def main():
    config.parse_args()
    logging.setup(CONF, 'keystone-playground')
    host = CONF.keystoneplayground.host
    port = CONF.keystoneplayground.port
    config_file = 'keystone-playground-paste.ini'
    config_file_path = CONF.find_file(config_file)
    config_file_path = os.path.abspath(config_file_path)
    app = loadapp("config:%s" % config_file_path)
    httpserver.serve(app, host=host, port=port)
Example #29
0
def main():
    # override annoying python SIGINT handling
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    parser = ArgumentParser(description="A webserver")
    parser.add_argument("-p", "--port", default=8080, type=int, help="Server port")
    args = parser.parse_args()

    routes = [(r"/.*", DumpHandler)]
    webapp = webapp2.WSGIApplication(routes=routes, debug=True)
    httpserver.serve(webapp, port=args.port, use_threadpool=True, daemon_threads=True)
 def serve(self, iceRenderMethod, icePreRenderMethod=None, icePostRenderMethod=None):
     self.__iceRenderMethod = iceRenderMethod
     self.__icePreRenderMethod = icePreRenderMethod
     self.__icePostRenderMethod = icePostRenderMethod
     
     app = self.__app
     if self.iceContext.settings.get("paste.profiling", False):
         from paste.debug.profile import ProfileMiddleware
         app = ProfileMiddleware(self.__app)
     
     httpserver.serve(app, host=self.__host, port=self.__port)
Example #31
0
def run():
    ##
    host = "localhost"
    port = 22345
    app = App()
    url = "http://%(host)s:%(port)d/" % vars()
    ##
    threading.Timer(2, open_url, (url, )).start()
    ##
    server = pserver.serve(app,
                           host=host,
                           port=port,
                           start_loop=False,
                           threadpool_workers=5)
    log.info("running server forever ..")
    server.serve_forever()
Example #32
0
 def __init__(self,
              nodepool,
              port=8005,
              listen_address='0.0.0.0',
              cache_expiry=1):
     threading.Thread.__init__(self)
     self.nodepool = nodepool
     self.port = port
     self.listen_address = listen_address
     self.cache = Cache(cache_expiry)
     self.cache_expiry = cache_expiry
     self.daemon = True
     self.server = httpserver.serve(dec.wsgify(self.app),
                                    host=self.listen_address,
                                    port=self.port,
                                    start_loop=False)
Example #33
0
def test_address_family_v4():
    #ipv4
    app = None
    host = '127.0.0.1'
    port = '9090'
    
    svr = serve(app, host=host, port=port, start_loop=False, use_threadpool=False)

    af = svr.address_family
    addr = svr.server_address
    p = svr.server_port
    
    svr.server_close()

    assert (af == socket.AF_INET)
    assert (addr[0] == '127.0.0.1')
    assert (str(p) == port)
Example #34
0
 def __init__(self,
              scheduler,
              port=8001,
              cache_expiry=1,
              listen_address='0.0.0.0'):
     threading.Thread.__init__(self)
     self.scheduler = scheduler
     self.listen_address = listen_address
     self.port = port
     self.cache_expiry = cache_expiry
     self.cache_time = 0
     self.cache = None
     self.daemon = True
     self.server = httpserver.serve(dec.wsgify(self.app),
                                    host=self.listen_address,
                                    port=self.port,
                                    start_loop=False)
Example #35
0
 def run(self):
     handler = bottle.default_app()
     self.server = httpserver.serve(handler,
                                    host=self.host,
                                    port=self.port,
                                    start_loop=False,
                                    use_threadpool=False,
                                    **self.kwargs)
     print("web: serving on %s:%d at http://%s:%d" %
           (self.host, self.port, self.dhost, self.port))
     #print(self.server.thread_pool)
     self.running = True
     try:
         self.server.serve_forever(poll_interval=0.5)
     finally:
         self.running = False
     print("web: Server thread exited")
Example #36
0
def serve_webapp(webapp, port=None, host=None):
    """Serve the webapp on a recommend port or a free one.

    Return the port the webapp is running on.
    """
    server = None
    for port in attempt_ports(port):
        try:
            server = httpserver.serve(webapp, host=host, port=port, start_loop=False)
            break
        except socket.error as e:
            if e[0] == 98:
                continue
            raise

    t = threading.Thread(target=server.serve_forever)
    t.start()

    return server, port
Example #37
0
def Main(argv):
    parser = argparse.ArgumentParser(description='Run development server')
    parser.add_argument('-p', '--port', default=8003, type=int)
    args = parser.parse_args(args=argv[1:])

    app = CreateApp()

    server = httpserver.serve(app,
                              host='127.0.0.1',
                              port=args.port,
                              start_loop=False)

    _AddPleaseExitMixinToServer(server)
    app.server = server

    sys.stderr.write('Now running on http://127.0.0.1:%i\n' %
                     server.server_port)

    return server.serve_forever()
Example #38
0
def test_address_family_v6():
    #ipv6
    app = None
    host = '[::1]'
    port = '9090'
    
    try:
        svr = serve(app, host=host, port=port, start_loop=False, use_threadpool=False)
        
        af = svr.address_family
        addr = svr.server_address
        p = svr.server_port

        svr.server_close()
        
        assert (af == socket.AF_INET6)
        assert (addr[0] == '::1')
        assert (str(p) == port)
    except (socket.error, OSError) as err:
        # v6 support not available in this OS, pass the test
        assert True
Example #39
0
    def launch(self, app=None, host='0.0.0.0'):
        """
        Some instance are registred there
            - server: wsgi server
            - host: wsgi server host
            - port: wsgi server port
            - app: the Pylon wsgi application
            - t: the thread where the server is running in
        """
        if not app:
            app = getApp()
        self.app = app
        self.host = host
        self.port = get_port()
        self.server = serve(
            self.app,
            self.host,
            self.port,
            socket_timeout=1,
            start_loop=False,
        )

        def server_close(self):
            """
            Finish pending requests and shutdown the server.
            """
            self.running = False
            self.socket.close()
            self.thread_pool.shutdown(1)

        def mainloop():
            """Handle requests."""
            self.server.server_close = server_close
            self.server.serve_forever()

        self.t = threading.Thread(target=mainloop)
        self.t.setDaemon(False)
        self.t.start()
Example #40
0
def Main(argv):
    pds = [
        perf_insights_dev_server_config.PerfInsightsDevServerConfig(),
        tracing_dev_server_config.TracingDevServerConfig(),
    ]

    args = _AddCommandLineArguments(pds, argv)

    if args.install_hooks:
        install.InstallHooks()

    app = CreateApp(pds, args)

    server = httpserver.serve(app,
                              host='127.0.0.1',
                              port=args.port,
                              start_loop=False)
    _AddPleaseExitMixinToServer(server)
    app.server = server

    sys.stderr.write('Now running on http://127.0.0.1:%i\n' %
                     server.server_port)

    return server.serve_forever()
Example #41
0
def Main(argv):
  pds = [
      dashboard_dev_server_config.DashboardDevServerConfig(),
      tracing_dev_server_config.TracingDevServerConfig(),
      netlog_viewer_dev_server_config.NetlogViewerDevServerConfig(),
  ]

  args = _AddCommandLineArguments(pds, argv)

  if args.install_hooks:
    install.InstallHooks()

  app = DevServerApp(pds, args=args)

  server = httpserver.serve(app, host='127.0.0.1', port=args.port,
                            start_loop=False, daemon_threads=True)
  _AddPleaseExitMixinToServer(server)
  # pylint: disable=no-member
  server.urlbase = 'http://127.0.0.1:%i' % server.server_port
  app.server = server

  sys.stderr.write('Now running on %s\n' % server.urlbase)

  return server.serve_forever()
Example #42
0
def paste_adapter(host, port, application):
    # Experimental (Untested).
    from paste import httpserver
    httpserver.serve(application, host=host, port=str(port))
Example #43
0
 def run(self, handler):
     from paste import httpserver
     from paste.translogger import TransLogger
     app = TransLogger(handler)
     httpserver.serve(app, host=self.host, port=str(self.port))
Example #44
0
 def paste(app, address, **options):
     from paste import httpserver
     from paste.translogger import TransLogger
     httpserver.serve(app, host=address[0], port=address[1], **options)
Example #45
0
import server
from paste.request import parse_formvars


def application(environ, start_response):
    path = environ["PATH_INFO"][1:] or "index"
    fields = parse_formvars(environ)
    if hasattr(server, path):
        try:
            body, ct = getattr(server, path)(**fields)
            code = "200 Success"
        except Exception as e:
            body, ct = "Error 500: " + type(e).__name__ + ": " + str(
                e), "text/plain"
            code = "500 Internal Server Error"
    else:
        body, ct = "Error 404: Page not found", "text/plain"
        code = "404 Page Not Found"

    response_headers = [("Content-type", ct),
                        ("Content-length", str(len(body)))]
    start_response(code, response_headers)
    return [unicode(body).encode("utf8")]


if __name__ == "__main__":
    from paste import httpserver
    httpserver.serve(application, host="18.248.3.226", port="8080")
Example #46
0
   config.add_view(add_host_apply_delete, route_name='add_host_apply_delete')

   config.add_route('delete_host', '/delete_host')
   config.add_view(delete_host, route_name='delete_host')

   config.add_route('edit_host', '/edit_host')
   config.add_view(edit_host, route_name='edit_host')

   config.add_route('add_test_form', '/add_test')
   config.add_view(add_test_form, route_name='add_test_form')

   config.add_route('add_test_apply', '/add_test_apply')
   config.add_view(add_test_apply, route_name='add_test_apply')

   config.add_route('add_test_apply_delete', '/add_test_apply_delete')
   config.add_view(add_test_apply_delete, route_name='add_test_apply_delete')

   config.add_route('delete_test', '/delete_test')
   config.add_view(delete_test, route_name='delete_test')

   config.add_route('edit_test', '/edit_test')
   config.add_view(edit_test, route_name='edit_test')

   config.add_route('run_tests', '/run_tests')
   config.add_view(run_tests, route_name='run_tests')

   config.add_static_view(name='static', path=os.getcwd() + '/static')

   app = config.make_wsgi_app()
   serve(app, host='0.0.0.0')
Example #47
0
    assert "current value is: 1" in res
    res = app.get("/")
    res = app.get("/")
    assert "current value is: 3" in res
    old_id = re.sub(r"^.*?session id is (\S+)$", r"\1",
                    res.body.decode("utf-8"), re.M)

    # Clear the cookies and do a new request
    app = TestApp(SessionMiddleware(simple_app, **options))
    res = app.get("/")
    assert "current value is: 1" in res

    # Load a bogus session to see that its not there
    res = app.get("/", extra_environ={"SESSION_ID": "jil2j34il2j34ilj23"})
    assert "No session id of" in res

    # Saved session was at 3, now it'll be 4
    res = app.get("/", extra_environ={"SESSION_ID": str(old_id)})
    assert "current value is: 4" in res

    # Prior request is now up to 2
    res = app.get("/")
    assert "current value is: 2" in res


if __name__ == "__main__":
    from paste import httpserver

    wsgi_app = SessionMiddleware(simple_app, {})
    httpserver.serve(wsgi_app, host="127.0.0.1", port=8080)
def main():
    from paste import httpserver
    httpserver.serve(application, host='127.0.0.1', port='8080')
Example #49
0
    (options, args) = api.bootstrap_with_global_options(parser, context='lite')
    api.env._merge(
        lite_port=options.port,
        lite_host=options.host,
        webui_prod=options.prod,
        lite_pem=api.env._join('dot_ipa', 'lite.pem'),
    )
    api.finalize()

    urlmap = URLMap()
    apps = [
        ('IPA', KRBCheater(api.Backend.wsgi_dispatch)),
        ('webUI', KRBCheater(WebUIApp())),
    ]
    for (name, app) in apps:
        urlmap[app.url] = app
        api.log.info('Mounting %s at %s', name, app.url)

    if path.isfile(api.env.lite_pem):
        pem = api.env.lite_pem
    else:
        api.log.info('To enable SSL, place PEM file at %r', api.env.lite_pem)
        pem = None

    httpserver.serve(
        paste.gzipper.middleware(urlmap),
        host=api.env.lite_host,
        port=api.env.lite_port,
        ssl_pem=pem,
    )
Example #50
0
def main():
    if install_and_test_base_util.tool_shed_api_key is None:
        # If the tool shed URL specified in any dict is not present in the tool_sheds_conf.xml, the installation will fail.
        log.debug(
            'Cannot proceed without a valid tool shed API key set in the enviroment variable GALAXY_INSTALL_TEST_TOOL_SHED_API_KEY.'
        )
        return 1
    if install_and_test_base_util.galaxy_tool_shed_url is None:
        log.debug(
            'Cannot proceed without a valid Tool Shed base URL set in the environment variable GALAXY_INSTALL_TEST_TOOL_SHED_URL.'
        )
        return 1
    # ---- Configuration ------------------------------------------------------
    galaxy_test_host = os.environ.get(
        'GALAXY_INSTALL_TEST_HOST',
        install_and_test_base_util.default_galaxy_test_host)
    # Set the GALAXY_INSTALL_TEST_HOST variable so that Twill will have the Galaxy url to which to
    # install repositories.
    os.environ['GALAXY_INSTALL_TEST_HOST'] = galaxy_test_host
    # Set the GALAXY_TEST_HOST environment variable so that the toolbox tests will have the Galaxy url
    # on which to to run tool functional tests.
    os.environ['GALAXY_TEST_HOST'] = galaxy_test_host
    galaxy_test_port = os.environ.get(
        'GALAXY_INSTALL_TEST_PORT',
        str(install_and_test_base_util.default_galaxy_test_port_max))
    os.environ['GALAXY_TEST_PORT'] = galaxy_test_port
    tool_path = os.environ.get('GALAXY_INSTALL_TEST_TOOL_PATH', 'tools')
    if 'HTTP_ACCEPT_LANGUAGE' not in os.environ:
        os.environ['HTTP_ACCEPT_LANGUAGE'] = default_galaxy_locales
    galaxy_test_file_dir = os.environ.get('GALAXY_INSTALL_TEST_FILE_DIR',
                                          default_galaxy_test_file_dir)
    if not os.path.isabs(galaxy_test_file_dir):
        galaxy_test_file_dir = os.path.abspath(galaxy_test_file_dir)
    use_distributed_object_store = os.environ.get(
        'GALAXY_INSTALL_TEST_USE_DISTRIBUTED_OBJECT_STORE', False)
    if not os.path.isdir(galaxy_test_tmp_dir):
        os.mkdir(galaxy_test_tmp_dir)
    # Set up the configuration files for the Galaxy instance.
    galaxy_shed_tool_path = os.environ.get(
        'GALAXY_INSTALL_TEST_SHED_TOOL_PATH',
        tempfile.mkdtemp(dir=galaxy_test_tmp_dir, prefix='shed_tools'))
    shed_tool_data_table_conf_file = os.environ.get(
        'GALAXY_INSTALL_TEST_SHED_TOOL_DATA_TABLE_CONF',
        os.path.join(galaxy_test_tmp_dir,
                     'test_shed_tool_data_table_conf.xml'))
    galaxy_tool_data_table_conf_file = os.environ.get(
        'GALAXY_INSTALL_TEST_TOOL_DATA_TABLE_CONF',
        install_and_test_base_util.tool_data_table_conf)
    galaxy_tool_conf_file = os.environ.get(
        'GALAXY_INSTALL_TEST_TOOL_CONF',
        os.path.join(galaxy_test_tmp_dir, 'test_tool_conf.xml'))
    galaxy_job_conf_file = os.environ.get(
        'GALAXY_INSTALL_TEST_JOB_CONF',
        os.path.join(galaxy_test_tmp_dir, 'test_job_conf.xml'))
    galaxy_shed_tool_conf_file = os.environ.get(
        'GALAXY_INSTALL_TEST_SHED_TOOL_CONF',
        os.path.join(galaxy_test_tmp_dir, 'test_shed_tool_conf.xml'))
    galaxy_migrated_tool_conf_file = os.environ.get(
        'GALAXY_INSTALL_TEST_MIGRATED_TOOL_CONF',
        os.path.join(galaxy_test_tmp_dir, 'test_migrated_tool_conf.xml'))
    galaxy_tool_sheds_conf_file = os.environ.get(
        'GALAXY_INSTALL_TEST_TOOL_SHEDS_CONF',
        os.path.join(galaxy_test_tmp_dir, 'test_tool_sheds_conf.xml'))
    galaxy_shed_tools_dict_file = os.environ.get(
        'GALAXY_INSTALL_TEST_SHED_TOOL_DICT_FILE',
        os.path.join(galaxy_test_tmp_dir, 'shed_tool_dict'))
    install_and_test_base_util.populate_galaxy_shed_tools_dict_file(
        galaxy_shed_tools_dict_file, shed_tools_dict=None)
    # Set the GALAXY_TOOL_SHED_TEST_FILE environment variable to the path of the shed_tools_dict file so that
    # test.base.twilltestcase.setUp will find and parse it properly.
    os.environ['GALAXY_TOOL_SHED_TEST_FILE'] = galaxy_shed_tools_dict_file
    if 'GALAXY_INSTALL_TEST_TOOL_DATA_PATH' in os.environ:
        tool_data_path = os.environ.get('GALAXY_INSTALL_TEST_TOOL_DATA_PATH')
    else:
        tool_data_path = tempfile.mkdtemp(dir=galaxy_test_tmp_dir)
        os.environ['GALAXY_INSTALL_TEST_TOOL_DATA_PATH'] = tool_data_path
    # Configure the database connection and path.
    if 'GALAXY_INSTALL_TEST_DBPATH' in os.environ:
        galaxy_db_path = os.environ['GALAXY_INSTALL_TEST_DBPATH']
    else:
        tempdir = tempfile.mkdtemp(dir=galaxy_test_tmp_dir)
        galaxy_db_path = os.path.join(tempdir, 'database')
    # Configure the paths Galaxy needs to install and test tools.
    galaxy_file_path = os.path.join(galaxy_db_path, 'files')
    new_repos_path = tempfile.mkdtemp(dir=galaxy_test_tmp_dir)
    galaxy_tempfiles = tempfile.mkdtemp(dir=galaxy_test_tmp_dir)
    galaxy_migrated_tool_path = tempfile.mkdtemp(dir=galaxy_test_tmp_dir)
    # Set up the tool dependency path for the Galaxy instance.
    tool_dependency_dir = os.environ.get(
        'GALAXY_INSTALL_TEST_TOOL_DEPENDENCY_DIR', None)
    if tool_dependency_dir is None:
        tool_dependency_dir = tempfile.mkdtemp(dir=galaxy_test_tmp_dir)
        os.environ[
            'GALAXY_INSTALL_TEST_TOOL_DEPENDENCY_DIR'] = tool_dependency_dir
    os.environ['GALAXY_TOOL_DEPENDENCY_DIR'] = tool_dependency_dir
    if 'GALAXY_INSTALL_TEST_DBURI' in os.environ:
        database_connection = os.environ['GALAXY_INSTALL_TEST_DBURI']
    else:
        database_connection = 'sqlite:///' + os.path.join(
            galaxy_db_path, 'install_and_test_repositories.sqlite')
    if 'GALAXY_INSTALL_TEST_INSTALL_DBURI' in os.environ:
        install_database_connection = os.environ[
            'GALAXY_INSTALL_TEST_INSTALL_DBURI']
    elif asbool(
            os.environ.get('GALAXY_TEST_INSTALL_DB_MERGED',
                           default_install_db_merged)):
        install_database_connection = database_connection
    else:
        install_galaxy_db_path = os.path.join(galaxy_db_path, 'install.sqlite')
        install_database_connection = 'sqlite:///%s' % install_galaxy_db_path
    kwargs = {}
    for dir in [galaxy_test_tmp_dir]:
        try:
            os.makedirs(dir)
        except OSError:
            pass
    print "Database connection: ", database_connection
    print "Install database connection: ", install_database_connection
    # Generate the shed_tool_data_table_conf.xml file.
    file(shed_tool_data_table_conf_file, 'w').write(
        install_and_test_base_util.tool_data_table_conf_xml_template)
    os.environ[
        'GALAXY_INSTALL_TEST_SHED_TOOL_DATA_TABLE_CONF'] = shed_tool_data_table_conf_file
    # ---- Start up a Galaxy instance ------------------------------------------------------
    # Generate the tool_conf.xml file.
    file(galaxy_tool_conf_file,
         'w').write(install_and_test_base_util.tool_conf_xml)
    # Generate the job_conf.xml file.
    file(galaxy_job_conf_file,
         'w').write(install_and_test_base_util.job_conf_xml)
    # Generate the tool_sheds_conf.xml file, but only if a the user has not specified an existing one in the environment.
    if 'GALAXY_INSTALL_TEST_TOOL_SHEDS_CONF' not in os.environ:
        file(galaxy_tool_sheds_conf_file,
             'w').write(install_and_test_base_util.tool_sheds_conf_xml)
    # Generate the shed_tool_conf.xml file.
    install_and_test_base_util.populate_shed_conf_file(
        galaxy_shed_tool_conf_file, galaxy_shed_tool_path, xml_elems=None)
    os.environ[
        'GALAXY_INSTALL_TEST_SHED_TOOL_CONF'] = galaxy_shed_tool_conf_file
    # Generate the migrated_tool_conf.xml file.
    install_and_test_base_util.populate_shed_conf_file(
        galaxy_migrated_tool_conf_file,
        galaxy_migrated_tool_path,
        xml_elems=None)
    # Write the embedded web application's specific configuration to a temporary file. This is necessary in order for
    # the external metadata script to find the right datasets.
    kwargs = dict(
        admin_users='*****@*****.**',
        master_api_key=install_and_test_base_util.
        default_galaxy_master_api_key,
        allow_user_creation=True,
        allow_user_deletion=True,
        allow_library_path_paste=True,
        database_connection=database_connection,
        datatype_converters_config_file="datatype_converters_conf.xml.sample",
        file_path=galaxy_file_path,
        id_secret=install_and_test_base_util.galaxy_encode_secret,
        install_database_connection=install_database_connection,
        job_config_file=galaxy_job_conf_file,
        job_queue_workers=5,
        log_destination="stdout",
        migrated_tools_config=galaxy_migrated_tool_conf_file,
        new_file_path=galaxy_tempfiles,
        running_functional_tests=True,
        shed_tool_data_table_config=shed_tool_data_table_conf_file,
        shed_tool_path=galaxy_shed_tool_path,
        template_path="templates",
        tool_config_file=','.join(
            [galaxy_tool_conf_file, galaxy_shed_tool_conf_file]),
        tool_data_path=tool_data_path,
        tool_dependency_dir=tool_dependency_dir,
        tool_path=tool_path,
        tool_parse_help=False,
        tool_sheds_config_file=galaxy_tool_sheds_conf_file,
        update_integrated_tool_panel=False,
        use_heartbeat=False)
    if os.path.exists(galaxy_tool_data_table_conf_file):
        kwargs[
            'tool_data_table_config_path'] = galaxy_tool_data_table_conf_file
    galaxy_config_file = os.environ.get('GALAXY_INSTALL_TEST_INI_FILE', None)
    # If the user has passed in a path for the .ini file, do not overwrite it.
    if not galaxy_config_file:
        galaxy_config_file = os.path.join(
            galaxy_test_tmp_dir,
            'install_test_tool_shed_repositories_wsgi.ini')
        config_items = []
        for label in kwargs:
            config_tuple = label, kwargs[label]
            config_items.append(config_tuple)
        # Write a temporary file, based on galaxy.ini.sample, using the configuration options defined above.
        generate_config_file('config/galaxy.ini.sample', galaxy_config_file,
                             config_items)
    kwargs['tool_config_file'] = [
        galaxy_tool_conf_file, galaxy_shed_tool_conf_file
    ]
    # Set the global_conf[ '__file__' ] option to the location of the temporary .ini file, which gets passed to set_metadata.sh.
    kwargs['global_conf'] = install_and_test_base_util.get_webapp_global_conf()
    kwargs['global_conf']['__file__'] = galaxy_config_file
    # ---- Build Galaxy Application --------------------------------------------------
    if not database_connection.startswith('sqlite://'):
        kwargs['database_engine_option_max_overflow'] = '20'
        kwargs['database_engine_option_pool_size'] = '10'
    kwargs['config_file'] = galaxy_config_file
    app = UniverseApplication(**kwargs)
    database_contexts.galaxy_context = app.model.context
    database_contexts.install_context = app.install_model.context

    log.debug("Embedded Galaxy application started...")
    # ---- Run galaxy webserver ------------------------------------------------------
    server = None
    global_conf = install_and_test_base_util.get_webapp_global_conf()
    global_conf['database_file'] = database_connection
    webapp = buildapp.app_factory(
        global_conf,
        use_translogger=False,
        static_enabled=install_and_test_base_util.STATIC_ENABLED,
        app=app)
    # Serve the app on a specified or random port.
    if galaxy_test_port is not None:
        server = httpserver.serve(webapp,
                                  host=galaxy_test_host,
                                  port=galaxy_test_port,
                                  start_loop=False)
    else:
        random.seed()
        for i in range(0, 9):
            try:
                galaxy_test_port = str(
                    random.randint(
                        install_and_test_base_util.
                        default_galaxy_test_port_min,
                        install_and_test_base_util.default_galaxy_test_port_max
                    ))
                log.debug(
                    "Attempting to serve app on randomly chosen port: %s",
                    galaxy_test_port)
                server = httpserver.serve(webapp,
                                          host=galaxy_test_host,
                                          port=galaxy_test_port,
                                          start_loop=False)
                break
            except socket.error, e:
                if e[0] == 98:
                    continue
                raise
        else:
Example #51
0
respectively.
"""

from authkit.authenticate import middleware, sample_app
from beaker.middleware import SessionMiddleware


def user_data(state):
    return 'User data string'


app = middleware(
    sample_app,
    setup_method='form,cookie',
    cookie_secret='secret encryption string',
    form_authenticate_user_data="""
        الإعلاني:9406649867375c79247713a7fb81edf0
        username2:4e64aba9f0305efa50396584cfbee89c
    """,
    form_authenticate_user_encrypt='authkit.users:md5',
    form_authenticate_user_encrypt_secret='some secret string',
    form_charset='UTF-8',
    cookie_signoutpath='/signout',
    cookie_nouserincookie=True,
    form_userdata=user_data,
)
app = SessionMiddleware(app, key='authkit.session', secret="some secret")
if __name__ == '__main__':
    from paste.httpserver import serve
    serve(app, host='0.0.0.0', port=8080)
Example #52
0
from stuffindex import utils
from stuffindex.application import application
from stuffindex.pages import pages
from paste import httpserver
from paste.cascade import Cascade
from paste.urlparser import StaticURLParser

static = StaticURLParser("./")

app = Cascade([application, static])

if __name__ == "__main__":
    print "blah"
    httpserver.serve(app, host="", port="8080")
    print "blah blah"
Example #53
0
        self.response.headers.add_header("X-XSS-Protection", "0")

        next_ = self.request.get('next')

        if next_ and 'javascript:' in next_:
            self.response.out.write('Invalid next path')
        else:
            # Route the request to the appropriate template
            if "signup" in self.request.path:
                self.response.out.write(
                    render('signup.html', {'next': next_})
                )
            elif "confirm" in self.request.path:
                self.response.out.write(
                    render(
                        'confirm.html',
                        {'next': next_},
                    )
                )
            else:
                self.response.out.write(render('welcome.html', {}))


application = webapp.WSGIApplication([('.*', MainPage)], debug=False)


if __name__ == '__main__':
    from paste import httpserver

    httpserver.serve(application, host='127.0.0.1', port='8080')
Example #54
0
def main():
    from paste import httpserver
    httpserver.serve(app, host='127.0.0.1', port='8000')
Example #55
0
def test_cookie_id():
    options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
               'session.type':'cookie'}
    app = TestApp(SessionMiddleware(simple_app, **options))
    res = app.get('/')
    assert "_id':" in res
    sess_id = re.sub(r".*'_id': '(.*?)'.*", r'\1', res.body)
    res = app.get('/')
    new_id = re.sub(r".*'_id': '(.*?)'.*", r'\1', res.body)
    assert new_id == sess_id

def test_invalidate_with_save_does_not_delete_session():
    def invalidate_session_app(environ, start_response):
        session = environ['beaker.session']
        session.invalidate()
        session.save()
        start_response('200 OK', [('Content-type', 'text/plain')])
        return ['Cookie is %s' % session]

    options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
               'session.type':'cookie'}
    app = TestApp(SessionMiddleware(invalidate_session_app, **options))
    res = app.get('/')
    assert 'expires=' not in res.headers.getall('Set-Cookie')[0]

if __name__ == '__main__':
    from paste import httpserver
    wsgi_app = SessionMiddleware(simple_app, {})
    httpserver.serve(wsgi_app, host='127.0.0.1', port=8080)
Example #56
0
        input_timezone = environ['PATH_INFO'][1:]
        if input_timezone:
            try:
                input_timezone = timezone(input_timezone)
            except UnknownTimeZoneError:
                start_response('200 OK', [('Content-Type', 'text/plain')])
                return [b'Unknown time zone']
        else:
            input_timezone = None

        msg = 'Time '
        if input_timezone:
            msg += 'in %s:\n' % input_timezone
        else:
            msg += 'on server:\n'

        start_response('200 OK', [('Content-Type', 'text/plain')])
        return [
            bytes(msg + datetime.now(tz=input_timezone).time().isoformat() +
                  '\nAdd needed timezone to the url\n',
                  encoding='utf-8')
        ]


if __name__ == '__main__':
    from paste import reloader
    from paste.httpserver import serve

    reloader.install()
    serve(app)
Example #57
0
from webob import Response
from webob.dec import wsgify
from paste import httpserver
from paste.deploy import loadapp
import os
import sys

ini_path = os.path.normpath(
    os.path.join(os.path.abspath(sys.argv[0]), os.pardir, 'api-paste.ini'))


@wsgify
def application(request):
    return Response('Hello, World of WebOb !\n')


def app_factory(global_config, **local_config):
    return application


if not os.path.isfile(ini_path):
    print("Cannot find api-paste.ini.\n")
    exit(1)

wsgi_app = loadapp('config:' + ini_path)
httpserver.serve(wsgi_app, host='0.0.0.0', port=8080)
Example #58
0
#encoding=utf-8
"""
Una aplicación sencilla que se apega al protocolo WSGI
"""


def application(environ, start_response):
    text = 'Hola Mundo!'
    start_response(
        #status
        "200 OK",
        #headers
        [('Content-Type', 'text/plain'), ('Content-Length', str(len(text)))])
    return [text]


from paste.httpserver import serve
serve(application)
Example #59
0
def main():
    # ---- Configuration ------------------------------------------------------
    galaxy_test_host = os.environ.get( 'GALAXY_TEST_HOST', default_galaxy_test_host )
    galaxy_test_port = os.environ.get( 'GALAXY_TEST_PORT', None )
    galaxy_test_save = os.environ.get( 'GALAXY_TEST_SAVE', None)
    tool_path = os.environ.get( 'GALAXY_TEST_TOOL_PATH', 'tools' )
    if 'HTTP_ACCEPT_LANGUAGE' not in os.environ:
        os.environ[ 'HTTP_ACCEPT_LANGUAGE' ] = default_galaxy_locales
    testing_migrated_tools = __check_arg( '-migrated' )
    testing_installed_tools = __check_arg( '-installed' )
    datatypes_conf_override = None

    if testing_migrated_tools or testing_installed_tools:
        # Store a jsonified dictionary of tool_id : GALAXY_TEST_FILE_DIR pairs.
        galaxy_tool_shed_test_file = 'shed_tools_dict'
        # We need the upload tool for functional tests, so we'll create a temporary tool panel config that defines it.
        fd, tmp_tool_panel_conf = tempfile.mkstemp()
        os.write( fd, '<?xml version="1.0"?>\n' )
        os.write( fd, '<toolbox>\n' )
        os.write( fd, '<tool file="data_source/upload.xml"/>\n' )
        os.write( fd, '</toolbox>\n' )
        os.close( fd )
        tool_config_file = tmp_tool_panel_conf
        galaxy_test_file_dir = None
        library_import_dir = None
        user_library_import_dir = None
        # Exclude all files except test_toolbox.py.
        ignore_files = ( re.compile( r'^test_[adghlmsu]*' ), re.compile( r'^test_ta*' ) )
    else:
        framework_tool_dir = os.path.join('test', 'functional', 'tools')
        framework_test = __check_arg( '-framework' )  # Run through suite of tests testing framework.
        if framework_test:
            tool_conf = os.path.join( framework_tool_dir, 'samples_tool_conf.xml' )
            datatypes_conf_override = os.path.join( framework_tool_dir, 'sample_datatypes_conf.xml' )
        else:
            # Use tool_conf.xml toolbox.
            tool_conf = None
            if __check_arg( '-with_framework_test_tools' ):
                tool_conf = "%s,%s" % ( 'config/tool_conf.xml.sample', os.path.join( framework_tool_dir, 'samples_tool_conf.xml' ) )
        test_dir = default_galaxy_test_file_dir
        tool_config_file = os.environ.get( 'GALAXY_TEST_TOOL_CONF', tool_conf )
        galaxy_test_file_dir = os.environ.get( 'GALAXY_TEST_FILE_DIR', test_dir )
        first_test_file_dir = galaxy_test_file_dir.split(",")[0]
        if not os.path.isabs( first_test_file_dir ):
            first_test_file_dir = os.path.join( os.getcwd(), first_test_file_dir )
        library_import_dir = first_test_file_dir
        import_dir = os.path.join( first_test_file_dir, 'users' )
        if os.path.exists(import_dir):
            user_library_import_dir = import_dir
        else:
            user_library_import_dir = None
        ignore_files = ()

    start_server = 'GALAXY_TEST_EXTERNAL' not in os.environ
    tool_data_table_config_path = None
    if os.path.exists( 'tool_data_table_conf.test.xml' ):
        # If explicitly defined tables for test, use those.
        tool_data_table_config_path = 'tool_data_table_conf.test.xml'
    else:
        # ... otherise find whatever Galaxy would use as the default and
        # the sample data for fucntional tests to that.
        default_tool_data_config = 'config/tool_data_table_conf.xml.sample'
        for tool_data_config in ['config/tool_data_table_conf.xml', 'tool_data_table_conf.xml' ]:
            if os.path.exists( tool_data_config ):
                default_tool_data_config = tool_data_config
        tool_data_table_config_path = '%s,test/functional/tool-data/sample_tool_data_tables.xml' % default_tool_data_config

    default_data_manager_config = 'config/data_manager_conf.xml.sample'
    for data_manager_config in ['config/data_manager_conf.xml', 'data_manager_conf.xml' ]:
        if os.path.exists( data_manager_config ):
            default_data_manager_config = data_manager_config
    data_manager_config_file = "%s,test/functional/tools/sample_data_manager_conf.xml" % default_data_manager_config
    shed_tool_data_table_config = 'config/shed_tool_data_table_conf.xml'
    tool_dependency_dir = os.environ.get( 'GALAXY_TOOL_DEPENDENCY_DIR', None )
    use_distributed_object_store = os.environ.get( 'GALAXY_USE_DISTRIBUTED_OBJECT_STORE', False )
    galaxy_test_tmp_dir = os.environ.get( 'GALAXY_TEST_TMP_DIR', None )
    if galaxy_test_tmp_dir is None:
        galaxy_test_tmp_dir = tempfile.mkdtemp()

    galaxy_job_conf_file = os.environ.get( 'GALAXY_TEST_JOB_CONF',
                                           os.path.join( galaxy_test_tmp_dir, 'test_job_conf.xml' ) )
    # Generate the job_conf.xml file.
    file( galaxy_job_conf_file, 'w' ).write( job_conf_xml )

    database_auto_migrate = False

    galaxy_test_proxy_port = None
    if start_server:
        tempdir = tempfile.mkdtemp( dir=galaxy_test_tmp_dir )
        # Configure the database path.
        if 'GALAXY_TEST_DBPATH' in os.environ:
            galaxy_db_path = os.environ[ 'GALAXY_TEST_DBPATH' ]
        else:
            galaxy_db_path = os.path.join( tempdir, 'database' )
        # Configure the paths Galaxy needs to  test tools.
        file_path = os.path.join( galaxy_db_path, 'files' )
        new_file_path = tempfile.mkdtemp( prefix='new_files_path_', dir=tempdir )
        job_working_directory = tempfile.mkdtemp( prefix='job_working_directory_', dir=tempdir )
        install_database_connection = os.environ.get( 'GALAXY_TEST_INSTALL_DBURI', None )
        if 'GALAXY_TEST_DBURI' in os.environ:
            database_connection = os.environ['GALAXY_TEST_DBURI']
        else:
            db_path = os.path.join( galaxy_db_path, 'universe.sqlite' )
            if 'GALAXY_TEST_DB_TEMPLATE' in os.environ:
                # Middle ground between recreating a completely new
                # database and pointing at existing database with
                # GALAXY_TEST_DBURI. The former requires a lot of setup
                # time, the latter results in test failures in certain
                # cases (namely tool shed tests expecting clean database).
                log.debug( "Copying database template from %s.", os.environ['GALAXY_TEST_DB_TEMPLATE'] )
                __copy_database_template(os.environ['GALAXY_TEST_DB_TEMPLATE'], db_path)
                database_auto_migrate = True
            database_connection = 'sqlite:///%s' % db_path
        kwargs = {}
        for dir in file_path, new_file_path:
            try:
                if not os.path.exists( dir ):
                    os.makedirs( dir )
            except OSError:
                pass

    # Data Manager testing temp path
    # For storing Data Manager outputs and .loc files so that real ones don't get clobbered
    data_manager_test_tmp_path = tempfile.mkdtemp( prefix='data_manager_test_tmp', dir=galaxy_test_tmp_dir )
    galaxy_data_manager_data_path = tempfile.mkdtemp( prefix='data_manager_tool-data', dir=data_manager_test_tmp_path )

    # ---- Build Application --------------------------------------------------
    master_api_key = get_master_api_key()
    app = None
    if start_server:
        kwargs = dict( admin_users='*****@*****.**',
                       api_allow_run_as='*****@*****.**',
                       allow_library_path_paste=True,
                       allow_user_creation=True,
                       allow_user_deletion=True,
                       database_connection=database_connection,
                       database_auto_migrate=database_auto_migrate,
                       datatype_converters_config_file="datatype_converters_conf.xml.sample",
                       file_path=file_path,
                       id_secret='changethisinproductiontoo',
                       job_queue_workers=5,
                       job_working_directory=job_working_directory,
                       library_import_dir=library_import_dir,
                       log_destination="stdout",
                       new_file_path=new_file_path,
                       running_functional_tests=True,
                       shed_tool_data_table_config=shed_tool_data_table_config,
                       template_path="templates",
                       test_conf="test.conf",
                       tool_config_file=tool_config_file,
                       tool_data_table_config_path=tool_data_table_config_path,
                       tool_path=tool_path,
                       galaxy_data_manager_data_path=galaxy_data_manager_data_path,
                       tool_parse_help=False,
                       update_integrated_tool_panel=False,
                       use_heartbeat=False,
                       user_library_import_dir=user_library_import_dir,
                       master_api_key=master_api_key,
                       use_tasked_jobs=True,
                       cleanup_job='onsuccess',
                       enable_beta_tool_formats=True,
                       data_manager_config_file=data_manager_config_file )
        if install_database_connection is not None:
            kwargs[ 'install_database_connection' ] = install_database_connection
        if not database_connection.startswith( 'sqlite://' ):
            kwargs[ 'database_engine_option_max_overflow' ] = '20'
            kwargs[ 'database_engine_option_pool_size' ] = '10'
        if tool_dependency_dir is not None:
            kwargs[ 'tool_dependency_dir' ] = tool_dependency_dir
        if use_distributed_object_store:
            kwargs[ 'object_store' ] = 'distributed'
            kwargs[ 'distributed_object_store_config_file' ] = 'distributed_object_store_conf.xml.sample'
        if datatypes_conf_override:
            kwargs[ 'datatypes_config_file' ] = datatypes_conf_override
        # If the user has passed in a path for the .ini file, do not overwrite it.
        galaxy_config_file = os.environ.get( 'GALAXY_TEST_INI_FILE', None )
        if not galaxy_config_file:
            galaxy_config_file = os.path.join( galaxy_test_tmp_dir, 'functional_tests_wsgi.ini' )
            config_items = []
            for label in kwargs:
                config_tuple = label, kwargs[ label ]
                config_items.append( config_tuple )
            # Write a temporary file, based on config/galaxy.ini.sample, using the configuration options defined above.
            generate_config_file( 'config/galaxy.ini.sample', galaxy_config_file, config_items )
        # Set the global_conf[ '__file__' ] option to the location of the temporary .ini file, which gets passed to set_metadata.sh.
        kwargs[ 'global_conf' ] = get_webapp_global_conf()
        kwargs[ 'global_conf' ][ '__file__' ] = galaxy_config_file
        kwargs[ 'config_file' ] = galaxy_config_file
        kwargs = load_app_properties(
            kwds=kwargs
        )
        # Build the Universe Application
        app = UniverseApplication( **kwargs )
        database_contexts.galaxy_context = app.model.context
        log.info( "Embedded Universe application started" )

    # ---- Run webserver ------------------------------------------------------
    server = None

    if start_server:
        webapp = buildapp.app_factory( kwargs[ 'global_conf' ], app=app,
            use_translogger=False, static_enabled=STATIC_ENABLED )
        if galaxy_test_port is not None:
            server = httpserver.serve( webapp, host=galaxy_test_host, port=galaxy_test_port, start_loop=False )
        else:
            random.seed()
            for i in range( 0, 9 ):
                try:
                    galaxy_test_port = str( random.randint( default_galaxy_test_port_min, default_galaxy_test_port_max ) )
                    log.debug( "Attempting to serve app on randomly chosen port: %s" % galaxy_test_port )
                    server = httpserver.serve( webapp, host=galaxy_test_host, port=galaxy_test_port, start_loop=False )
                    break
                except socket.error, e:
                    if e[0] == 98:
                        continue
                    raise
            else:
                raise Exception( "Unable to open a port between %s and %s to start Galaxy server" % ( default_galaxy_test_port_min, default_galaxy_test_port_max ) )
Example #60
0
def main():
    from paste import httpserver
    httpserver.serve(app, host='0.0.0.0', port='8080')