def test(HandlerClass = CGIHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): import sys if sys.argv[1:2] == ['-r']: db = MyArchive() db.regenindices() return SimpleHTTPServer.test(HandlerClass, ServerClass)
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()
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)
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...'
#!/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
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)
}, '/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)
#!/usr/bin/env python import SimpleHTTPServer;SimpleHTTPServer.test()
def test(HandlerClass=SimpleAppServer, ServerClass=BaseHTTPServer.HTTPServer): SimpleHTTPServer.test(HandlerClass, ServerClass)
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)
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)
#! /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();
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)
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)
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)
#!/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)
# 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)
import SimpleHTTPServer as server server.test()
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()
def test(HandlerClass = SimpleAppServer, ServerClass = BaseHTTPServer.HTTPServer): SimpleHTTPServer.test(HandlerClass, ServerClass)
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)
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 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)
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())
def main(): SimpleHTTPServer.test()
def loadLog(): SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
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)
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)
#!/usr/bin/env python import BaseHTTPServer import SimpleHTTPServer import CGIHTTPServer if __name__ == '__main__': SimpleHTTPServer.test( CGIHTTPServer.CGIHTTPRequestHandler, BaseHTTPServer.HTTPServer)
def httpserver2(port): import SimpleHTTPServer sys.argv=['',port] SimpleHTTPServer.test(SimpleHTTPServer.SimpleHTTPRequestHandler)
"""CGI-savvy HTTP Server.
#!/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() #サーバ立ち上げ
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)
#!/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)
#!/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)
def test(HandlerClass=MultiViewsRequestHandler, ): SimpleHTTPServer.test(HandlerClass=HandlerClass)
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)
# 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
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)
def main(): SimpleHTTPServer.test(CGIHTTPRequestHandler, BaseHTTPServer.HTTPServer)
def main(argv): SimpleHTTPServer.test(EditRequestHandler, SocketServer.TCPServer)
import webbrowser as browser import os import SimpleHTTPServer as s browser.open('http://localhost:8000/test') s.test()
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)
#!/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)
############# # 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) #############
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)
import SimpleHTTPServer SimpleHTTPServer.test()
def testName(self): SimpleHTTPServer.test()
#!/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()
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)