Пример #1
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()
Пример #2
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)
Пример #3
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)
Пример #4
0
def main():
    pwd = os.getcwd()

    try:
        os.chdir("./docs")
        SimpleHTTPServer.test()
    finally:
        os.chdir(pwd)
Пример #5
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)
Пример #6
0
def run():
    import sys
    if sys.version_info < (3, 0, 0):
        # Python2系
        import SimpleHTTPServer as server
        server.test(HandlerClass=server.SimpleHTTPRequestHandler)
    else:
        # Python3系
        from http.server import HTTPServer, CGIHTTPRequestHandler
        host = 'localhost'
        port = 8000
        httpd = HTTPServer((host, port), CGIHTTPRequestHandler)
        print('serving at port', port)
        httpd.serve_forever()
Пример #7
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...'
def run_simple_server():
    _ = get_dataset('smallfile')
    _ = get_dataset('bigfile')
    _ = get_dataset_bz2('smallfile')
    _ = get_dataset_bz2('bigfile')
    os.chdir(DATA_DIR)
    if six.PY2:
        import SimpleHTTPServer
        import RangeHTTPServer
        from RangeHTTPServer import RangeRequestHandler
        import sys
        sys.argv[1] = 8000
        SimpleHTTPServer.test(HandlerClass=RangeRequestHandler)
    else:
        import RangeHTTPServer.__main__
Пример #9
0
 def do_GET(self):
     self.actfunc = {
         'checkpatch': self.checkpatch,
         'listinfo': self.listinfo,
         'addpatch': self.addpatch
     }
     f = SimpleHTTPServer.StringIO()
     #self.getcursor()
     #f.write('ok<br>')#this is request args::'+self.path+'<br>')
     if not self.dbisok(f):
         return
     self.parseARGS()
     if not self.argsdit:
         fp = os.getcwd() + self.path
         if os.path.isfile(fp):
             hf = open(fp)
             f.write(hf.read())
             hf.close()
         else:
             f.write("request page is not exist</br>")
         self.senddata(f, 200, 'PAGE')
         return
     if not self.argsdit.get('func'):
         f.write('this request have not a function <br>')
         self.senddata(f, 201, 'NOTFUNC')
         return
     if self.actfunc.get(self.argsdit['func']):
         self.actfunc[self.argsdit['func']](f)
     else:
         f.write('this request have a nonexist function <br>')
         self.senddata(f, 202, 'NOTEXIST')
Пример #10
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

Пример #11
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)
Пример #12
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)
Пример #13
0
Файл: serve.py Проект: vic/ice
#!/usr/bin/env python
import SimpleHTTPServer;SimpleHTTPServer.test()
Пример #14
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)
#############
Пример #15
0
#!/usr/bin/env python
#encoding: utf8

import rospy, os
import SimpleHTTPServer

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

os.chdir(os.path.dirname(__file__)) #scriptsディレクトリが見えるように
rospy.init_node("webserver")        #rosのノード登録
rospy.on_shutdown(kill)             #kill関数の登録
SimpleHTTPServer.test()             #サーバ立ち上げ
Пример #16
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)
Пример #17
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)
#!/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)
Пример #19
0
def httpserver2(port):
    import SimpleHTTPServer
    sys.argv=['',port]
    SimpleHTTPServer.test(SimpleHTTPServer.SimpleHTTPRequestHandler)
Пример #20
0
import SimpleHTTPServer as server

server.test()
Пример #21
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()
Пример #22
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())
Пример #23
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)
Пример #24
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
Пример #25
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)
Пример #26
0
def main():
    SimpleHTTPServer.test(CGIHTTPRequestHandler, BaseHTTPServer.HTTPServer)
Пример #27
0
def test(HandlerClass=SimpleAppServer, ServerClass=BaseHTTPServer.HTTPServer):
    SimpleHTTPServer.test(HandlerClass, ServerClass)
Пример #28
0
import webbrowser as browser
import os

import SimpleHTTPServer as s


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

Пример #29
0
def test(HandlerClass = CGIHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    SimpleHTTPServer.test(HandlerClass, ServerClass)
Пример #30
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)
Пример #31
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)
def do_request(connstream, from_addr):
    x = object()
    SimpleHTTPServer.SimpleHTTPRequestHandler(connstream, from_addr, x)
Пример #33
0
#!/usr/bin/env python

import BaseHTTPServer
import SimpleHTTPServer
import CGIHTTPServer

if __name__ == '__main__':
    SimpleHTTPServer.test(
        CGIHTTPServer.CGIHTTPRequestHandler, BaseHTTPServer.HTTPServer)
Пример #34
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)
Пример #35
0
"""CGI-savvy HTTP Server.
Пример #36
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)
Пример #37
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)
Пример #38
0
 def testName(self):
     SimpleHTTPServer.test()
Пример #39
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)
Пример #40
0
def do_serve(args):
    os.chdir("_site")
    import SimpleHTTPServer
    sys.argv = [None, args.PORT]
    SimpleHTTPServer.test()
Пример #41
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)
Пример #42
0
def main():
    SimpleHTTPServer.test()
    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)
Пример #44
0
#! /usr/bin/env python
#-*- coding: utf-8 -*-
import rospy, os
import SimpleHTTPServer


def kill():
    os.system("kill -KILL " + str(os.getpid()))


os.chdir(os.path.dirname(__file__))
rospy.init_node("webserver")
rospy.on_shutdown(kill)
SimpleHTTPServer.test()
Пример #45
0
def main(argv):
    SimpleHTTPServer.test(EditRequestHandler, SocketServer.TCPServer)
Пример #46
0
#!/usr/bin/env python
import SimpleHTTPServer
# https://stackoverflow.com/questions/12193803/invoke-python-simplehttpserver-from-command-line-with-no-cache-option


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("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=MyHTTPRequestHandler)
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)
Пример #48
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)
Пример #49
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()
Пример #50
0
def loadLog():
  SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
Пример #51
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()
Пример #52
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)
Пример #53
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)
Пример #54
0
 def test(HandlerClass = SimpleAppServer,
          ServerClass = BaseHTTPServer.HTTPServer):
   SimpleHTTPServer.test(HandlerClass, ServerClass)
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)
Пример #56
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')
def test(HandlerClass=CGIHTTPRequestHandler,
         ServerClass=BaseHTTPServer.HTTPServer):
    SimpleHTTPServer.test(HandlerClass, ServerClass)
Пример #58
0
def create_server(server):
    change_dir()
    server = server.BaseHTTPServer.HTTPServer((local_ip(), 80),
                                              server.SimpleHTTPRequestHandler)
    print server.server_address
    server.serve_forever()