Exemplo n.º 1
0
def test(HandlerClass = CGIHTTPRequestHandler,
	 ServerClass = BaseHTTPServer.HTTPServer):
    import sys
    if sys.argv[1:2] == ['-r']:
	db = MyArchive()
	db.regenindices()
	return
    SimpleHTTPServer.test(HandlerClass, ServerClass)
Exemplo n.º 2
0
 def main(self):
     log.info("press '^C' to stop server")
     freezerDstPath = self.parent.projectPath / ProjectFinder.BUILD_DIR
     with local.cwd(freezerDstPath):
         sys.argv[1] = self.parent.PORT
         log.info("serve frozen flask from %s at http://localhost:%s",
                  freezerDstPath, self.parent.PORT)
         SimpleHTTPServer.test()
Exemplo n.º 3
0
def main():
    if len(sys.argv) < 2:
        sys.exit("Please supply a directory to serve")
    os.chdir(sys.argv[1])

    # Remove the directory from argv so the HTTP port can still be
    # specified after the directory (read by SimpleHTTPServer.test)
    del sys.argv[1]

    SimpleHTTPServer.test(ServerClass=ThreadingHTTPServer)
Exemplo n.º 4
0
def webshare(open_in_browser=False, port=8000):
    if open_in_browser:
        import webbrowser
        def open_in_browser():
            webbrowser.open_new_tab('http://localhost:{0}'.format(port))
        _delay_background(open_in_browser, 0.5)

    # BaseHTTPServer looks at argv[1] for port
    sys.argv = [sys.argv[0], port]
    import SimpleHTTPServer
    try:
        SimpleHTTPServer.test()
    except KeyboardInterrupt:
        print '\nStopping...'
Exemplo n.º 5
0
#!/usr/bin/env python
import subprocess as sub
import BaseHTTPServer
import SimpleHTTPServer as httpd


# override this method to speed up connection
def _bare_address_string(self):
    host, port = self.client_address[:2]
    return '%s' % host


BaseHTTPServer.BaseHTTPRequestHandler.address_string = _bare_address_string

# get ip address and print
info = sub.Popen('/sbin/ifconfig', stdout=sub.PIPE).communicate()[0]
tokens = []
for line in info.split('\n'):
    if 'inet' in line:
        if '127.0.0.1' not in line:
            tokens = line.split()
print("")
print("'    ', tokens[1].replace(':', ': '), '\n    ',")

# start server
try:
    httpd.test()
except KeyboardInterrupt:
    print('\x08\x08Killed')
# SimpleHTTPServer-to-allow-PUT-Method
import SimpleHTTPServer
import BaseHTTPServer

class SputHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_PUT(self):
        print self.headers
        length = int(self.headers["Content-Length"])
        path = '/root/Downloads/'
        with open(path, "wb") as dst:
            dst.write(self.rfile.read(length))


if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=SputHTTPRequestHandler
Exemplo n.º 7
0
def test(HandlerClass = CGIHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    SimpleHTTPServer.test(HandlerClass, ServerClass)
import mimetypes
import SimpleHTTPServer
import BaseHTTPServer

class LocalHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    """SimpleHTTPServer subclass which knows about certain necessary MIME types."""

    SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map.update({
        '.svg': 'image/svg+xml',
        })

if __name__ == '__main__':
    SimpleHTTPServer.test(LocalHTTPRequestHandler, BaseHTTPServer.HTTPServer)
    def end_headers(self):
        self.githubpages_headers()
        SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)

    """Agrega headers que usa GHP"""
    def githubpages_headers(self):
        timestamp = time.time() + 600
        year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
        s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
                self.weekdayname[wd],
                day, self.monthname[month], year,
                hh, mm, ss)
        self.send_header("Cache-Control", "max-age=600")
        self.send_header("Expires", s)

    """Asegura el Content-type correcto para el manifest appcache (=GHP)"""
    def guess_type(self, path):
        mimetype = SimpleHTTPServer.SimpleHTTPRequestHandler.guess_type(
            self, path
        )
        if path.endswith('.appcache'):
            mimetype = 'text/cache-manifest'
        return mimetype



if __name__ == '__main__':
    print "\n* Iniciando servidor local."
    print "Puede iniciar este script indicando un numero de puerto si desea.\n"
    SimpleHTTPServer.test(HandlerClass=GPlikeRequestHandler)
Exemplo n.º 10
0
            },
            '/js/event-data.gz': {
                'Content-Encoding': 'gzip',
                'Content-Type': 'text/javascript'
            },
            '/js/jquery.gz': {
                'Content-Encoding': 'gzip',
                'Content-Type': 'text/javascript'
            },
            '/js/d3.gz': {
                'Content-Encoding': 'gzip',
                'Content-Type': 'text/javascript'
            },
            '/js/deparam.min.gz': {
                'Content-Encoding': 'gzip',
                'Content-Type': 'text/javascript'
            },
            '/js/mapbox.gz': {
                'Content-Encoding': 'gzip',
                'Content-Type': 'text/javascript'
            },
        }

        if self.path in MONKEYPATCHED_HEADERS:
            for header, value in MONKEYPATCHED_HEADERS[self.path].iteritems():
                self.send_header(header, value)


if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=GZipFriendlyRequestHandler)
Exemplo n.º 11
0
Arquivo: serve.py Projeto: vic/ice
#!/usr/bin/env python
import SimpleHTTPServer;SimpleHTTPServer.test()
Exemplo n.º 12
0
def test(HandlerClass=SimpleAppServer, ServerClass=BaseHTTPServer.HTTPServer):
    SimpleHTTPServer.test(HandlerClass, ServerClass)
Exemplo n.º 13
0
import SimpleHTTPServer


@contextlib.contextmanager
def working_directory(path):
    """A context manager which changes the working directory to the given
    path, and then changes it back to its previous value on exit.

    """
    prev_cwd = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(prev_cwd)


class NoCacheHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_my_headers()
        SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)

    def send_my_headers(self):
        self.send_header("Cache-Control",
                         "no-cache, no-store, must-revalidate")
        self.send_header("Pragma", "no-cache")
        self.send_header("Expires", "0")


if __name__ == '__main__':
    with working_directory("build"):
        SimpleHTTPServer.test(HandlerClass=NoCacheHTTPRequestHandler)
Exemplo n.º 14
0
import mimetypes
import SimpleHTTPServer
import BaseHTTPServer


class LocalHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """SimpleHTTPServer subclass which knows about certain necessary MIME types."""

    SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map.update({
        '.svg':
        'image/svg+xml',
    })


if __name__ == '__main__':
    SimpleHTTPServer.test(LocalHTTPRequestHandler, BaseHTTPServer.HTTPServer)
Exemplo n.º 15
0
            self.send_error(416, 'Requested Range Not Satisfiable')
            return None

        self.send_response(206)
        self.send_header('Content-type', ctype)
        self.send_header('Accept-Ranges', 'bytes')

        if last is None or last >= file_len:
            last = file_len - 1
        response_length = last - first + 1

        self.send_header('Content-Range',
                         'bytes %s-%s/%s' % (first, last, file_len))
        self.send_header('Content-Length', str(response_length))
        self.send_header('Last-Modified', self.date_time_string(fs.st_mtime))
        self.end_headers()
        return f

    def copyfile(self, source, outputfile):
        if not self.range:
            return SimpleHTTPRequestHandler.copyfile(self, source, outputfile)

        # SimpleHTTPRequestHandler uses shutil.copyfileobj, which doesn't let
        # you stop the copying before the end of the file.
        start, stop = self.range  # set in send_head()
        copy_byte_range(source, outputfile, start, stop)


if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=RangeRequestHandler)
Exemplo n.º 16
0
#! /usr/bin/env python
import SimpleHTTPServer; m = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map; m[''] = 'text/plain'; m.update(dict([(k, v + ';charset=UTF-8') for k, v in m.items()])); SimpleHTTPServer.test();
Exemplo n.º 17
0
            for index in "index.html", "index.htm":
                index = os.path.join(path, index)
                if os.path.exists(index):
                    path = index
                    break
            else:
                return self.list_directory(path)
        ctype = self.guess_type(path)
        try:
            # Always read in binary mode. Opening files in text mode may cause
            # newline translations, making the actual size of the content
            # transmitted *less* than the content-length!
            f = open(path, 'rb')
        except IOError:
            self.send_error(404, "File not found")
            return None
        self.send_response(200)
        self.send_header("Content-type", ctype)
        fs = os.fstat(f.fileno())
        self.send_header("Content-Length", str(fs[6]))
        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))

        if (path.endswith("kif") or path.endswith("kif.txt")):
            self.send_header("Pragma", "no-cache")

        self.end_headers()
        return f


SimpleHTTPServer.test(HookHTTPRequestHandler)
Exemplo n.º 18
0
import SimpleHTTPServer
import movieutil


class StreamingHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    def send_head(self):
        path = self.translate_path(self.path)
        if movieutil.is_movie(path):
            self.send_response(200)
            self.send_header("Content-type", 'video/x-matroska')
            self.end_headers()
            f = movieutil.transcode(path)
        else:
            f = SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
        return f


if __name__ == '__main__':
    SimpleHTTPServer.test(StreamingHTTPRequestHandler)
Exemplo n.º 19
0
                    fs_path = index
                    break

        if (fs_path.endswith('.html')
                or fs_path.endswith(".shtml")) and os.path.exists(fs_path):
            content = ssi.InlineIncludes(fs_path, path)
            fs_path = self.create_temp_file(fs_path, content)
        return fs_path

    def delete_temp_files(self):
        for temp_file in self.temp_files:
            os.remove(temp_file)

    def create_temp_file(self, original_path, content):
        _, ext = os.path.splitext(original_path)
        if ext == ".shtml":
            ext = ".html"
        fd, path = tempfile.mkstemp(suffix=ext)
        try:
            os.write(fd, content)  # This works for Python 2
        except TypeError:
            os.write(fd, bytes(content, 'UTF-8'))  # This works for Python 3
        os.close(fd)

        self.temp_files.append(path)
        return path


if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=SSIRequestHandler)
Exemplo n.º 20
0
#!/usr/bin/env python
# coding: utf-8
"""
usage: python httpsserver.py 443
"""

import sys
import ssl
import SocketServer
import BaseHTTPServer
import SimpleHTTPServer

# openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
CERT_FILE = './cert.pem'


class ThreadingSimpleServer(SocketServer.ThreadingMixIn,
                            BaseHTTPServer.HTTPServer):
    def get_request(self):
        conn, addr = self.socket.accept()
        sconn = ssl.wrap_socket(conn,
                                server_side=True,
                                certfile=CERT_FILE,
                                keyfile=CERT_FILE,
                                ssl_version=ssl.PROTOCOL_SSLv23)
        return (sconn, addr)


if __name__ == '__main__':
    SimpleHTTPServer.test(ServerClass=ThreadingSimpleServer)
Exemplo n.º 21
0
    # change to the kn_apps dir (as this basic HTTP server only references the
    # current directory and below)
    os.chdir(appsDir)

    # start out using the default mod_pubsub server address
    mpsServer = defaultMpsServer

    # read the prologue.js file to get the actual server address
    try:
        prologuePath = os.path.join(appsDir, 'kn_lib', 'prologue.js')
        mpsServer = readPubSubServerAddress (prologuePath)
    except IOError, (errno, strerror):
        sys.stderr.write(
            "Warning, problem accessing %s, (%s): %s\n" % (prologuePath, errno, strerror)
        )
        sys.stderr.flush()
        pass

    # set the PubSub Server name in the replacement list
    for i in range(0,len(replaceStrList)):
        replaceStrList[i] = replaceStrList[i] % mpsServer

    print "\nUsing mod_pubsub server: %s\n" % mpsServer

    SimpleHTTPServer.test(CrossDomainRequestHandler)

if __name__ == "__main__": main(sys.argv)

# End of xdomainserver.py

#!/usr/bin/env python

import SimpleHTTPServer


class NoCacheRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    def end_headers(self):
        self.send_my_headers()
        SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)

    def send_my_headers(self):
        self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
        self.send_header("Pragma", "no-cache")
        self.send_header("Expires", "0")


if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=NoCacheRequestHandler)
Exemplo n.º 23
0
import SimpleHTTPServer as server

server.test()

Exemplo n.º 24
0
def cli(ctx, **kwargs):
    '''aspath_graph converts raw ASPATHs to NetJSON Graph

    NetJSON is a series of JSON schema for defining networks, NetJSON Graph
    being specific to defining how nodes interconnect. "aspath_graph" uses this
    to represent BGP autonomous systems as 'nodes' and how they connect from
    the perspective of INPUT

    INPUT can either be a device or file depending on value of MODE. This
    defaults to a file. (txt)

    OUTPUT can be '-' to send results to STDOUT.

    If not passing '--nopassword', you will be prompted for a password for the
    relevant modes.

    When using "--asdot" to provide ASDOT notation, the raw ASPLAIN will also
    be provided on the node - just under the "raw" attribute. Note that without
    using this option, if an ASDOT exists in the INPUT data it will be
    represented still as ASPLAIN.

    YAML can be formatted as such: (Note that "ignore" must ONLY be ASPLAIN)

        \b
        ---
        label_map:
            65001: SFO
            65002: ORD
            65003: NYC
            65003.1: NYC-R1
            65003.2: NYC-R2
        ignore:
            - 7224
            - 9059

    By default, ASDOT will be labeled according to the firsthalf. Eg, if 65001
    is configured to be labeled as DFW, 65001.211 will appear as DFW-R21. This
    assumes your ToR ASN is your spine ASN + (racknumber*10+1) - to disable
    this simply set APG_ASDOT_RAW to true/yes/anything.

    Any of the supported options can be passed via ENV by upping the case,
    replacing '-' with '_', and prefixing with 'APG'. Eg, 'APG_MODE'
    '''
    LABEL_MAP, IGNORE_LIST = parse_yaml(kwargs['yaml'])
    raw_paths = []
    if kwargs['mode'] == 'txt':
        # Click can intelligently open standard streams and files
        with click.open_file(kwargs['input']) as f:
            raw_paths = f.readlines()

    elif kwargs['mode'] == 'junos-netconf':
        # This must return as a list of stringed paths (think readlines)
        raw_paths = netconf_paths(kwargs['input'], kwargs['user'],
                                  kwargs['nopassword'])

    all_nodes = set()
    all_pairs = set()
    for path_string in raw_paths:
        path_calc = link_paths(path_string, ownas=kwargs['ownas'])
        all_nodes.update(path_calc['nodes'])
        all_pairs.update(path_calc['pairs'])

    netjson = generate_netjson(all_nodes,
                               all_pairs,
                               lmap=LABEL_MAP,
                               ignore=IGNORE_LIST,
                               asdot=kwargs['asdot'],
                               ownas=kwargs['ownas'])

    if kwargs.get('pprint'):
        kwargs['output'].write(json.dumps(netjson, indent=2))
    else:
        kwargs['output'].write(json.dumps(netjson))

    if kwargs.get('runserver'):
        # This will change directory into the pkg's static directory, create
        # netjson.json, and run SimpleHTTPServer
        webpath = os.path.abspath(
            os.path.dirname(aspath_graph.__file__) + '/static')
        os.chdir(webpath)
        with open('netjson.json', 'w') as f:
            f.write(json.dumps(netjson))

        import sys
        sys.argv[1] = 8000
        SimpleHTTPServer.test()
Exemplo n.º 25
0
def test(HandlerClass = CGIHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    SimpleHTTPServer.test(HandlerClass, ServerClass)
Exemplo n.º 26
0
 def test(HandlerClass = SimpleAppServer,
          ServerClass = BaseHTTPServer.HTTPServer):
   SimpleHTTPServer.test(HandlerClass, ServerClass)
Exemplo n.º 27
0
import SimpleHTTPServer

class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_my_headers()

        SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)

    def send_my_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")


if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
Exemplo n.º 28
0
            for index in "index.html", "index.htm":
                index = os.path.join(path, index)
                if os.path.exists(index):
                    path = index
                    break
            else:
                return self.list_directory(path)
        ctype = self.guess_type(path)
        try:
            # Always read in binary mode. Opening files in text mode may cause
            # newline translations, making the actual size of the content
            # transmitted *less* than the content-length!
            f = open(path, "rb")
        except IOError:
            self.send_error(404, "File not found")
            return None
        self.send_response(200)
        self.send_header("Content-type", ctype)
        fs = os.fstat(f.fileno())
        self.send_header("Content-Length", str(fs[6]))
        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))

        if path.endswith("kif") or path.endswith("kif.txt"):
            self.send_header("Pragma", "no-cache")

        self.end_headers()
        return f


SimpleHTTPServer.test(HookHTTPRequestHandler)
Exemplo n.º 29
0
  def translate_path(self, path):
    fs_path = SimpleHTTPRequestHandler.translate_path(self, path)
    if self.path.endswith('/'):
      for index in "index.html", "index.htm":
        index = os.path.join(fs_path, index)
        if os.path.exists(index):
          fs_path = index
          break

    if fs_path.endswith('.html'):
      content = ssi.InlineIncludes(fs_path)
      fs_path = self.create_temp_file(fs_path, content)
    return fs_path

  def delete_temp_files(self):
    for temp_file in self.temp_files:
      os.remove(temp_file)

  def create_temp_file(self, original_path, content):
    _, ext = os.path.splitext(original_path)
    fd, path = tempfile.mkstemp(suffix=ext)
    os.write(fd, content)
    os.close(fd)

    self.temp_files.append(path)
    return path


if __name__ == '__main__':
  SimpleHTTPServer.test(HandlerClass=SSIRequestHandler)
Exemplo n.º 30
0
def main():
    args = parse_args()
    logger.setLevel(logging.ERROR-args.verbose*10)
    cfg = json.load(open(args.config))
    if args.profile is None:
        profile_name = cfg.get('default_profile',None)
    else:
        profile_name = args.profile

    if profile_name is not None:
        try:
            profile = cfg.get('profiles',{})[profile_name]
            cfg.update(profile)
        except KeyError as e:
            logger.fatal('No such profile '+ profile_name)
            logger.fatal('Available profiles:'+' '.join(cfg.get('profiles',{}).keys()))
            exit(1)

    if args.sources is None:
        args.sources=cfg.get('sources','source')
    if args.templates is None:
        args.templates=cfg.get('templates','templates')
    if args.website is None:
        args.website=cfg.get('website','website')
    if args.filters is None:
        args.filters=cfg.get('filters','filters')

    if args.command == 'compile' or args.command == 'list-assets':

        jinja_env.config = cfg
        jinja_env.filters['json']=json_filter
        jinja_env.filters['asset']=asset_filter
        jinja_env.filters['DOI']=doi_filter
        jinja_env.filters['VIMEO']=vimeo_filter
        jinja_env.filters['YOUTUBE']=youtube_filter
        jinja_env.filters['split']=split_filter

        try:
            custom_filters = __import__(args.filters)
            for f_name in custom_filters.__all__:
                logger.info("Loading filter %s",f_name)
                jinja_env.filters[f_name] = getattr(custom_filters,f_name)
        except Exception as ex:
            logger.error("Could not load custom filters: %s",repr(ex))

        jinja_env.tests['equalto']=equalto_test
        jinja_env.tests['not equalto']=equalto_test
        jinja_env.loader=jinja2.FileSystemLoader([args.templates])
        if 'assets' in cfg:
            jinja_env.assets = scan_assets(cfg['assets'])
        else:
            jinja_env.assets = {}
        jinja_env.missing_assets={}

        default_template_base = strip_extension(cfg.get('default_template','base.tpl'))
        tree = build_web_tree(args.sources,base_dir=args.sources,default_template_base=default_template_base)

        global_ctx={'type':type}
        global_ctx['website']=tree
        global_ctx['config']=cfg

        process_tree(tree,global_ctx,args.website,dry_run=(args.command =='list-assets'))

        if args.command == 'list-assets':
            for asset,data in jinja_env.assets.items():
                if data['copy']:
                    print(data['src'],'->',asset, data['hash'])
            if len(jinja_env.missing_assets) > 0:
                print("MISSING:")
                print("\t\n".join(jinja_env.missing_assets.keys()))
        else:
            if not args.skipassets:
                for (asset,data) in jinja_env.assets.items():
                    if data['copy']:
                        dest=args.website+'/'+asset
                        logger.info("Copying '"+data['src']+''" to '"+dest+"'")
                        cp(data['src'],dest,create_parents=True,filters=data['filters'])
                    else:
                        logger.info("Skipping '"+data['src']+"'")
            if len(jinja_env.missing_assets) > 0:
                logger.error("The following assets were not found:")
                logger.error(';'.join(jinja_env.missing_assets.keys()))


    elif args.command == 'serve':
        import SimpleHTTPServer
        sys.argv=['wg.py',str(args.port)]
        os.chdir(args.website)
        SimpleHTTPServer.test()

    elif args.command == 'list-formats':
        print("Metadata Formats:", META_FORMATS.keys())
        print("Content Formats:", CONTENT_FORMATS.keys())
Exemplo n.º 31
0
def main():
    SimpleHTTPServer.test()
Exemplo n.º 32
0
def cli(ctx, **kwargs):
    '''aspath_graph converts raw ASPATHs to NetJSON Graph

    NetJSON is a series of JSON schema for defining networks, NetJSON Graph
    being specific to defining how nodes interconnect. "aspath_graph" uses this
    to represent BGP autonomous systems as 'nodes' and how they connect from
    the perspective of INPUT

    INPUT can either be a device or file depending on value of MODE. This
    defaults to a file. (txt)

    OUTPUT can be '-' to send results to STDOUT.

    If not passing '--nopassword', you will be prompted for a password for the
    relevant modes.

    When using "--asdot" to provide ASDOT notation, the raw ASPLAIN will also
    be provided on the node - just under the "raw" attribute. Note that without
    using this option, if an ASDOT exists in the INPUT data it will be
    represented still as ASPLAIN.

    YAML can be formatted as such: (Note that "ignore" must ONLY be ASPLAIN)

        \b
        ---
        label_map:
            65001: SFO
            65002: ORD
            65003: NYC
            65003.1: NYC-R1
            65003.2: NYC-R2
        ignore:
            - 7224
            - 9059

    By default, ASDOT will be labeled according to the firsthalf. Eg, if 65001
    is configured to be labeled as DFW, 65001.211 will appear as DFW-R21. This
    assumes your ToR ASN is your spine ASN + (racknumber*10+1) - to disable
    this simply set APG_ASDOT_RAW to true/yes/anything.

    Any of the supported options can be passed via ENV by upping the case,
    replacing '-' with '_', and prefixing with 'APG'. Eg, 'APG_MODE'
    '''
    LABEL_MAP, IGNORE_LIST = parse_yaml(kwargs['yaml'])
    raw_paths = []
    if kwargs['mode'] == 'txt':
        # Click can intelligently open standard streams and files
        with click.open_file(kwargs['input']) as f:
            raw_paths = f.readlines()

    elif kwargs['mode'] == 'junos-netconf':
        # This must return as a list of stringed paths (think readlines)
        raw_paths = netconf_paths(kwargs['input'],
                                  kwargs['user'],
                                  kwargs['nopassword'])

    all_nodes = set()
    all_pairs = set()
    for path_string in raw_paths:
        path_calc = link_paths(path_string, ownas=kwargs['ownas'])
        all_nodes.update(path_calc['nodes'])
        all_pairs.update(path_calc['pairs'])

    netjson = generate_netjson(all_nodes, all_pairs,
                               lmap=LABEL_MAP, ignore=IGNORE_LIST,
                               asdot=kwargs['asdot'], ownas=kwargs['ownas'])

    if kwargs.get('pprint'):
        kwargs['output'].write(json.dumps(netjson, indent=2))
    else:
        kwargs['output'].write(json.dumps(netjson))

    if kwargs.get('runserver'):
        # This will change directory into the pkg's static directory, create
        # netjson.json, and run SimpleHTTPServer
        webpath = os.path.abspath(
                os.path.dirname(aspath_graph.__file__) + '/static')
        os.chdir(webpath)
        with open('netjson.json', 'w') as f:
            f.write(json.dumps(netjson))

        import sys
        sys.argv[1] = 8000
        SimpleHTTPServer.test()
Exemplo n.º 33
0
def loadLog():
  SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
Exemplo n.º 34
0
import SimpleHTTPServer as server

server.test()
Exemplo n.º 35
0
        except:
            self.send_response(200)
            self.send_header("Content-type", "text/plain")
            self.end_headers()
            self.wfile.write("Problem sending image: %s\n" % self.path)

    def do_GET(self):
        """Serve a GET request."""
        if self.path[:len("/quit")] == "/quit":
            self.send_response(200)
            self.send_header("Content-type", "text/plain")
            self.end_headers()
            self.wfile.write("exiting....")
            global cam
            del cam
            sys.exit(0)
        if self.path[:len("/cam")] == "/cam":
            self.sendImage()
            return
        if self.path[:len("/push")] == "/push":
            self.pushImages()
            return
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
        return


if len(sys.argv) == 1:
    sys.argv = (sys.argv[0], "8000")

SimpleHTTPServer.test(MyHandler)
Exemplo n.º 36
0
def main():
    if len(sys.argv) != 3: raise ValueError('usage: pyhpy.httpd PORT DOCROOT')
    setDOCROOT(os.path.abspath(sys.argv[2]))
    SimpleHTTPServer.test(HandlerClass=PyHPyHTTPRequestHandler)
Exemplo n.º 37
0
#!/usr/bin/env python

import BaseHTTPServer
import SimpleHTTPServer
import CGIHTTPServer

if __name__ == '__main__':
    SimpleHTTPServer.test(
        CGIHTTPServer.CGIHTTPRequestHandler, BaseHTTPServer.HTTPServer)
Exemplo n.º 38
0
def httpserver2(port):
    import SimpleHTTPServer
    sys.argv=['',port]
    SimpleHTTPServer.test(SimpleHTTPServer.SimpleHTTPRequestHandler)
Exemplo n.º 39
0
"""CGI-savvy HTTP Server.
Exemplo n.º 40
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import rospy, os
import SimpleHTTPServer


def kill():

    os.system("kill -KILL " + str(os.getpid()))  #強制シャットダウン


if __name__ == '__main__':

    os.chdir(os.path.dirname(__file__))  #scriptsディレクトリが見えるように
    rospy.init_node("webserver")  #rosのノード登録
    rospy.on_shutdown(kill)  #kill関数の登録
    SimpleHTTPServer.test()  #サーバ立ち上げ
Exemplo n.º 41
0
import SimpleHTTPServer

class CORSHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def end_headers(self):

        # Chrome won't load fonts without this header
        self.send_header('Access-Control-Allow-Origin', '*')

        SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)

if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=CORSHandler)
Exemplo n.º 42
0
#!/usr/bin/env python2
import SimpleHTTPServer
import os


class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
	def translate_path(self, path):
		if path.startswith("/~zhaoyich/"):
			path = path[len("/~zhaoyich/"):]
		return SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self, path)

if __name__ == "__main__":
	SimpleHTTPServer.test(MyHTTPRequestHandler)
Exemplo n.º 43
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if sys.version_info < (3, 0, 0):
    # Python2系
    import SimpleHTTPServer as server
else:
    # Python3系
    import http.server as server

server.test(HandlerClass=server.SimpleHTTPRequestHandler)
Exemplo n.º 44
0
def test(HandlerClass=MultiViewsRequestHandler, ):
    SimpleHTTPServer.test(HandlerClass=HandlerClass)
Exemplo n.º 45
0
import BaseHTTPServer, SimpleHTTPServer, CGIHTTPServer

class myRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
     def is_executable(self, path):
         return self.is_python(path)

if __name__ == '__main__':
     SimpleHTTPServer.test(myRequestHandler, BaseHTTPServer.HTTPServer)
Exemplo n.º 46
0
    # change to the kn_apps dir (as this basic HTTP server only references the
    # current directory and below)
    os.chdir(appsDir)

    # start out using the default mod_pubsub server address
    mpsServer = defaultMpsServer

    # read the prologue.js file to get the actual server address
    try:
        prologuePath = os.path.join(appsDir, 'kn_lib', 'prologue.js')
        mpsServer = readPubSubServerAddress(prologuePath)
    except IOError, (errno, strerror):
        sys.stderr.write("Warning, problem accessing %s, (%s): %s\n" %
                         (prologuePath, errno, strerror))
        sys.stderr.flush()
        pass

    # set the PubSub Server name in the replacement list
    for i in range(0, len(replaceStrList)):
        replaceStrList[i] = replaceStrList[i] % mpsServer

    print "\nUsing mod_pubsub server: %s\n" % mpsServer

    SimpleHTTPServer.test(CrossDomainRequestHandler)


if __name__ == "__main__":
    main(sys.argv)

    # End of xdomainserver.py
Exemplo n.º 47
0
            assert commands.getstatusoutput("python parse.py %s.json" %
                                            suite_name)[0] == 0
            zipfb = zipfile.ZipFile("%s.zip" % suite_name, "w")
            zipfb.write("%s.json" % suite_name)
            zipfb.write("%s.robot" % suite_name)
            zipfb.write("variable.py")
            zipfb.write("test_api.py")
            zipfb.close()
            abspath = os.path.realpath(".")
            self.send_response(200)
            self.send_header("Content-Length", len(abspath))
            self.send_header("Connection", "Close")
            self.end_headers()
            self.wfile.write(abspath)
        except:
            self.send_error(500)

    def do_POST(self):
        action = self.distribute_action()
        if not action:
            self.send_error(404)
            return
        else:
            action()


if __name__ == "__main__":
    SimpleHTTPServer.test(
        HandlerClass=CustomHTTPRequestHandler,
        ServerClass=SimpleHTTPServer.BaseHTTPServer.HTTPServer)
Exemplo n.º 48
0
def main():
    SimpleHTTPServer.test(CGIHTTPRequestHandler, BaseHTTPServer.HTTPServer)
Exemplo n.º 49
0
def main(argv):
    SimpleHTTPServer.test(EditRequestHandler, SocketServer.TCPServer)
Exemplo n.º 50
0
import webbrowser as browser
import os

import SimpleHTTPServer as s


browser.open('http://localhost:8000/test')
s.test()

Exemplo n.º 51
0
            with open("../suites/%s/%s.json" %(folder_name, suite_name), "w") as fb:
                json.dump(request_data["suite_data"], fb, indent=4) 
                fb.flush()
            os.chdir("../suites/%s" %folder_name)
            assert commands.getstatusoutput("python parse.py %s.json" %suite_name)[0]==0
            zipfb = zipfile.ZipFile("%s.zip" %suite_name, "w")
            zipfb.write("%s.json" %suite_name)
            zipfb.write("%s.robot" %suite_name)
            zipfb.write("variable.py")
            zipfb.write("test_api.py")
            zipfb.close()
            abspath = os.path.realpath(".")
            self.send_response(200)
            self.send_header("Content-Length", len(abspath))
            self.send_header("Connection", "Close")
            self.end_headers()
            self.wfile.write(abspath)
        except:
            self.send_error(500)

    def do_POST(self):
        action = self.distribute_action()
        if not action:
            self.send_error(404)
            return
        else:
            action()

if __name__=="__main__":
    SimpleHTTPServer.test(HandlerClass=CustomHTTPRequestHandler, ServerClass=SimpleHTTPServer.BaseHTTPServer.HTTPServer)
Exemplo n.º 52
0
#!/usr/bin/env python
import SimpleHTTPServer


class RefreshingRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header("Refresh", "1")
        SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)


if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=RefreshingRequestHandler)
Exemplo n.º 53
0
#############
# webserver.py
import BaseHTTPServer, SimpleHTTPServer, CGIHTTPServer

class myRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
     def is_executable(self, path):
         return self.is_python(path)

if __name__ == '__main__':
     SimpleHTTPServer.test(myRequestHandler, BaseHTTPServer.HTTPServer)
#############
Exemplo n.º 54
0
        out_file.seek(0)
        return out_file

    def send_head(self):
        path = self.translate_path(self.path)
        if path.endswith(".tsv"):
            try:
                with open(path, "rb") as orig_file:
                    encoding = self.file_encoding
                    tsv_contents = unicode(orig_file.read(), encoding)
                    rows = [line.split("\t") for line in tsv_contents.splitlines()]
                return self._render_table(rows, encoding)
            except UnicodeDecodeError:
                # default behaviour
                pass
        return _server.SimpleHTTPRequestHandler.send_head(self)


class LocalHTTPServer(_b_server.HTTPServer):
    """Inheritor of the BaseHTTPServer.HTTPServer that runs strictly on 127.0.0.1"""

    def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
        # serve only on 127.0.0.1, port is taken from the input
        server_address = ("127.0.0.1", server_address[1])

        _s_server.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)


if __name__ == "__main__":
    _server.test(HandlerClass=TSVHandler, ServerClass=LocalHTTPServer)
Exemplo n.º 55
0
import SimpleHTTPServer

SimpleHTTPServer.test()
Exemplo n.º 56
0
 def testName(self):
     SimpleHTTPServer.test()
Exemplo n.º 57
0
#!/usr/bin/python

import sys
import SimpleHTTPServer

program = sys.argv[0]

# Tell Simple HTTP Server to use port 80
# Note: this requires root permission
sys.argc = 2
sys.argv = [program, '80']

SimpleHTTPServer.test()
Exemplo n.º 58
0
def do_serve(args):
    os.chdir("_site")
    import SimpleHTTPServer
    sys.argv = [None, args.PORT]
    SimpleHTTPServer.test()
import SimpleHTTPServer
import logging

cookieHeader = None


class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.cookieHeader = self.headers.get('Cookie')
        print self.headers
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)


    def end_headers(self):
        self.send_my_headers()

        SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)

    def send_my_headers(self):
	self.send_header("Set-Cookie", "_cfuididi=0b59c51aca680614ad7d395510880dd7")

if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
Exemplo n.º 60
0
import SimpleHTTPServer


class CORSHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def end_headers(self):

        # Chrome won't load fonts without this header
        self.send_header('Access-Control-Allow-Origin', '*')

        SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)


if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=CORSHandler)