Beispiel #1
0
def run(pargs=None, name=None):
    args, parser = parse_args(pargs=pargs, name=name)
    logconfig(args.quiet, args.verbose)  # configure logging

    # Determine if dev mode is active to build an on-the-fly bundle
    args.dev = any(getattr(args, x) for x in dir(args) if x.startswith('dev_'))

    if args.auto_serve:
        args.dev = True

        args.auto_serve = os.path.normpath(args.auto_serve)
        if os.path.isdir(args.auto_serve):
            # Get first .py file
            root, dnames, fnames = next(os.walk(args.auto_serve))
            found = None
            for fname in fnames:
                _, ext = os.path.splitext(fname)
                if ext == '.py':
                    args.auto_serve = found = os.path.join(root, fname)
                    break

            if found is None:
                logging.error('No .py script in auto_serve dir: %s'
                              % args.auto_serve)
                sys.exit(1)

        elif not os.path.isfile(args.auto_serve):
            logging.error('auto_serve % not found' % args.auto_serve)
            sys.exit(1)

    logging.debug('args.dev is %s', str(args.dev))

    if args.api_url:
        if not args.api_url.startswith('/'):
            args.api_url = '/' + args.api_url

        if not args.api_url.startswith('/'):
            args.api_url += '/'

        args.api_url = posixpath.normpath(args.api_url)

        # Check the mod
        apimod, e = loadmodule(args.api_mod)
        if apimod is None:
            logging.error('API URL specified: %s', args.api_url)
            logging.error('But cannot load API Module: %s', args.api_mod)
            sys.exit(1)

        # Check the data
        apidata = getattr(apimod, args.api_data, None)
        if apidata is None:
            logging.error('API URL specified: %s', args.api_url)
            logging.error('API Module Loaded: %s', args.api_mod)
            logging.error('But cannot find API Data: %s', args.api_data)
            sys.exit(1)

        try:
            args.api_idata = {d[args.api_index]: d for d in apidata}
        except KeyError:
            logging.error('API URL specified: %s', args.api_url)
            logging.error('API Module Loaded: %s', args.api_mod)
            logging.error('API Data found')
            logging.error('Failed to find index in  data: %s', args.api_index)
            sys.exit(1)

        args.api_hidx = max(args.api_idata.keys())

    srvaddr = ('', args.port)
    handlercls = SimpleHTTPRequestHandler if args.simple else RequestHandler

    logging.info('%s: Server Starts - %s', time.asctime(), str(srvaddr))

    # rework the application path for sanity
    args._spath = args.application.replace('\\', '/')
    if args._spath[-1] != '/':
        args._spath += '/'  # make sure it has a trailing slath

    # to allow restarting the server in short succession
    socketserver.TCPServer.allow_reuse_address = True

    httpd = HTTPServer(srvaddr, handlercls)
    httpd.cliargs = args

    if args.browser:  # try to open a browser if needed
        url = 'http://{}:{}'.format(httpd.server_name, httpd.server_port)
        webbrowser.open_new_tab(url)

    # needed to avoid potential process deadlocks under windows if run as child
    win_wait_for_parent()

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        httpd.server_close()

    logging.info('%s: Server Stops - %s', time.asctime(), str(srvaddr))