def test(): try: HandlerClass = ProxyHTTPRequestHandler ServerClass = ThreadingHTTPServer BaseHTTPServer.test(HandlerClass, ServerClass) except: print "sering exit!" sys._exit(1)
def main(): handler = CGIHTTPServer.CGIHTTPRequestHandler handler.cgi_directories = ['/cgi-bin'] if sys.argv[1:]: os.chdir(sys.argv[1]) sys.argv.pop(1) BaseHTTPServer.test(HandlerClass=handler)
def main(): if APP_KEY == '' or APP_SECRET == '': exit("You need to set your APP_KEY and APP_SECRET!") if len(sys.argv) == 1: print "usage: python web_example.py [PORT]" port = sys.argv[1] if len(sys.argv) > 1 else "8000" print "Browse to http://localhost:%s to try this app." % port BaseHTTPServer.test(ExampleHandler, BaseHTTPServer.HTTPServer)
def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('port', help='port number to listen on (by default 80)', default=8080, type=int, nargs='?') parser.add_argument('-4', help="use IPv4", action="store_false", dest='use_ipv6') parser.add_argument('-6', help="use IPv6 (default)", action="store_true", dest='use_ipv6', default=True) args = parser.parse_args() if args.use_ipv6: ServerClass = HTTPServerV6 else: ServerClass = HTTPServerV4 # BaseHTTPServer.test() expects just one positional argument sys.argv[1:] = [ args.port ] BaseHTTPServer.test(RequestHandler, ServerClass)
def test(HandlerClass = SimpleHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): """Run the HTTP request handler class. This runs an HTTP server on port 8000 (or the first command line argument). """ parse_options() server_address = ('127.0.0.1', SERVER_PORT) SimpleHTTPRequestHandler.protocol_version = "HTTP/1.0" httpd = BaseHTTPServer.HTTPServer(server_address, SimpleHTTPRequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() BaseHTTPServer.test(HandlerClass, ServerClass)
def __getHtmlFeed(self, fromDate, toDate): def compare(a, b): return cmp(a[1], b[1]) try: rows = self.feeder.getFeed(fromDate, toDate, True) rows.sort(compare) data = "" for file, eventTime, eventName, isDir in rows: data += "%s, %s, %s, %s\n" % (eventTime, eventName, file, isDir) data = BaseHTTPServer._quote_html(data).replace("\n", "<br/>") #if True: try: if rows==[]: t = self.feeder.convertGMTToInteger(fromDate) else: t = rows[-1][1] lastModified = self.feeder.formatDateTime(t, utc=True) data += "<br/>lastModified=%s" % lastModified except Exception, e: print str(e) print "t='%s'" % t except Exception, e: data = str({"Error": str(e)})
def __getFeedText(self, fromDate, toDate): def compare(a, b): return cmp(a[1], b[1]) try: rows = self.feeder.getFeed(fromDate, toDate, True) rows.sort(compare) data = "" for file, eventTime, eventName, isDir in rows: data += "%s, %s, %s, %s\n" % (eventTime, eventName, file, isDir) data = BaseHTTPServer._quote_html(data) # if True: try: if rows == []: lastModified = fromDate # lastModified = self.feeder.formatDateTime(fromDate, utc=True) else: lastModified = rows[-1][1] data += "\nlastModified = %s" % lastModified except Exception, e: print str(e) print "t='%s'" % t except Exception, e: data = str({"Error": str(e)})
# Source: https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server # PYTHON 2 ONLY from SimpleHTTPServer import SimpleHTTPRequestHandler import BaseHTTPServer class CORSHandler(SimpleHTTPRequestHandler): def end_headers(self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': BaseHTTPServer.test(CORSHandler, BaseHTTPServer.HTTPServer)
parms = queryparser.parse(path) res = '<h3> Parâmetros:</h3>\n' for k in parms.keys(): res += '<p>'+k+'="'+parms[k]+'"\n' return res # o servidor class ServidorExemplo(BaseHTTPServer.BaseHTTPRequestHandler): # tratamento de uma requisicao GET def do_GET(self): print self.path self.send_response(200) self.send_header("Content-type","text/json") self.end_headers() #self.wfile.write(htmlpage.replace('[parms]',getParms(self.path))) self.wfile.write(resposta(self.path)) # tratamento de uma requisicao POST def do_POST(self): self.wfile.write("<HTML><body>Operação POST não permitida.<BR><BR></body></HTML>"); # criação do servidor httpserver = BaseHTTPServer.HTTPServer(("",8080), ServidorExemplo) # rodar até ... httpserver.serve_forever() # testar com: http://localhost:8080//?vulcao=Eyjafallajokull&evento=erupcao&dia=0&hora=0&op=ca
def test(HandlerClass=SimpleHTTPRequestHandler, ServerClass=BaseHTTPServer.HTTPServer, filename="HTTP"): BaseHTTPServer.test(HandlerClass, ServerClass, filename=filename)
# A simple test server for responding in different ways to SvnPubSub clients. # This avoids the complexity of the Twisted framework in order to direct # various (abnormal) conditions at the client. # # ### usage... # import sys import BaseHTTPServer PORT = 2069 TEST_BODY = '<commit repository="12345678-1234-1234-1234-123456789012" revision="1234"><author>johndoe</author><date>2012-01-01 01:01:01 +0000 (Sun, 01 Jan 2012)</date><log>Frob the ganoozle with the snookish</log><dirs_changed><path>one/path/</path><path>some/other/directory/</path></dirs_changed></commit>' SEND_KEEPALIVE = True class TestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-Length', str(len(TEST_BODY))) self.send_header('Connection', 'keep-alive') self.end_headers() self.wfile.write(TEST_BODY) if __name__ == '__main__': server = BaseHTTPServer.HTTPServer(('', PORT), TestHandler) sys.stderr.write('Now listening on port %d...\n' % (PORT, )) server.serve_forever()
def handler(HandlerClass=HTTPRequestHandler, ServerClass=BaseHTTPServer.HTTPServer): # test method is used to run on local host BaseHTTPServer.test(HandlerClass, ServerClass)
# return list of files if path == "list/" or path == "list": return os.path.join(data_dir, "") # return index file if path == "": return os.path.join(website_dir, "tracelogger.html") # return data files if os.path.isdir(os.path.join(data_dir, path)) or path.endswith(".json") or path.endswith(".tl"): return os.path.join(data_dir, path) # return website UI return os.path.join(website_dir, path) if __name__ == '__main__': # Interpret non-numeric first argument as a data directory. if len(sys.argv) > 1: try: port = int(sys.argv[1]) except: data_dir = sys.argv.pop(1) if data_dir is None: data_dir = os.getcwd() # If not running from within the website/ directory, assume we are running # from the data directory. cd to the website dir so we serve non-data files # from there. website_dir = os.path.realpath(os.path.dirname(__file__)) os.chdir(website_dir) BaseHTTPServer.test(TraceLoggerRequestHandler, BaseHTTPServer.HTTPServer)
print "\t" "idle", count if count == max_idling: break do_HEAD = do_GET do_POST = do_GET do_PUT = do_GET do_DELETE = do_GET class ThreadingHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass if __name__ == '__main__': from sys import argv if argv[1:] and argv[1] in ('-h', '--help'): print argv[0], "[port [allowed_client_name ...]]" else: if argv[2:]: allowed = [] for name in argv[2:]: client = socket.gethostbyname(name) allowed.append(client) print "Accept: %s (%s)" % (client, name) ProxyHandler.allowed_clients = allowed del argv[2:] else: print "Any clients will be served..." BaseHTTPServer.test(ProxyHandler, ThreadingHTTPServer)
import BaseHTTPServer import subprocess import sys class Handler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(original_page) def do_PUT(self): try: n = int(self.headers["Content-Length"]) new_page = self.rfile.read(n) open(fn, 'w').write(new_page) print 'saved', n, 'bytes to', fn except Exception as e: print e port = 8888 fn = sys.argv[1] original_page = open(fn).read() httpd = BaseHTTPServer.HTTPServer(('localhost', 8888), Handler) url = 'http://localhost:{port}/{fn}'.format(port=port, fn=fn) subprocess.call(['open', url]) httpd.serve_forever()
import logging import cgi class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): logging.error(self.headers) SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) def do_POST(self): logging.error(self.headers) form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) for item in form.list: logging.error(item) SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) Handler = ServerHandler httpd = BaseHTTPServer.HTTPServer(('10.1.1.185', 443), Handler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./server.pem', server_side=True) httpd.serve_forever()
import BaseHTTPServer import SimpleHTTPServer import ssl httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket(httpd.socket, keyfile='key.pem', certfile='cert.pem', server_side=True) httpd.serve_forever()
import BaseHTTPServer import SimpleHTTPServer import subprocess class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_POST(self): f = self.send_head() if f: try: self.copyfile(f, self.wfile) print('POST request accepted') finally: f.close() httpd = BaseHTTPServer.HTTPServer(('', 8200), RequestHandler) httpd.serve_forever()
"resource_uri": "/api/v1/facility/2/" }, "resource_uri": "/api/v1/instrument/31/" }], "resource_uri": "/api/v1/mydata_uploader/25/", }] } self.wfile.write(json.dumps(uploadersJson)) else: raise Exception("FakeMyTardis Server doesn't know how to respond " "to PUT: %s" % self.path) def log_message(self, format, *args): # pylint: disable=redefined-builtin """ Supressing logging of HTTP requests to STDERR. """ return if __name__ == '__main__': HTTPD = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER), FakeMyTardisHandler) print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER) try: HTTPD.serve_forever() except KeyboardInterrupt: pass HTTPD.server_close() print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
def do_GET(self): if self.path != "/hchan.jpg": hostname = socket.gethostname() message_parts = [ "<html>", "<head><title>Hello World</title></head>", "<body style=\"text-align:center;\">", "<p><img src='hchan.jpg' /></p>", "<h3>Hello Alauda!</h3><br />", "<p>My hostname is <b>" + hostname + "</b></p>", "</body>", "<html>" ] message = '\r\n'.join(message_parts) print message # message = "New request arrived from %s:%d" % self.client_address self.send_response(200) self.end_headers() self.wfile.write(message) else: f = open(os.curdir + os.sep + self.path) self.send_response(200) self.send_header('Content-type', 'image/jpg') self.end_headers() self.wfile.write(f.read()) f.close() if __name__ == '__main__': print "Server started, Listening on port 80" server = BaseHTTPServer.HTTPServer(('0.0.0.0', 80), WebRequestHandler) server.serve_forever()
def test(HandlerClass=MediaRequestHandler, ServerClass=BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
def main(): addr = ('', SETTINGS['port']) server = BaseHTTPServer.HTTPServer(addr, HTTPHandler) print 'Running ImpactJS Server\nGame: http://localhost:%d\nEditor: http://localhost:%d/editor' % (addr[1], addr[1]) server.serve_forever()
return None try: with open(path, 'r') as fp: source = fp.read() fs = os.fstat(fp.fileno()) except IOError: return None output = markdown.markdown(source.decode(_CHARSET), extensions=_EXTENSIONS) html = _HTML_TEMPLATE.format(title=os.path.basename(path), charset=_CHARSET, body=output.encode(_CHARSET)) self.send_response(200) self.send_header('Content-Type', 'text/html; charset=' + _CHARSET) self.send_header('Content-Length', len(html)) self.send_header('Last-Modified', self.date_time_string(fs.st_mtime)) self.end_headers() return cStringIO.StringIO(html) def send_head(self): markdown = self._render_markdown() if markdown: return markdown return SimpleHTTPRequestHandler.send_head(self) if __name__ == '__main__': BaseHTTPServer.test(HandlerClass=EzgfmHandler)
responseJson["total_nodes"] = global_blockchain.get_nodes() responseData = json.dumps(responseJson) return responseData # ノードを確認する def _do_get_nodes_resolve(self): is_keep = global_blockchain.resolve_conflicts() responseJson = {} responseJson[ "message"] = "チェーンが置き換えられました" if is_keep else "チェーンが確認されました" responseJson["chain"] = global_blockchain.get_chain() responseData = json.dumps(responseJson) return responseData # 送信情報作成関数 def write_response(self, code, type, data): self.send_response(code) self.send_header("Content-type", type) self.end_headers() self.wfile.write(data) if __name__ == "__main__": print("Starting server {} use <Ctrl-C> to stop").format(global_node) BaseHTTPServer.HTTPServer(("", global_port), TestHTTPRequestHandler).serve_forever() # ---------------------------------------------------------------- # ---------------------------------------------------------------- # ----------------------------------------------------------------
def main(HandlerClass = CaptchaHTTPServer, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
def test(HandlerClass=ReactTutorialHTTPRequestHandler, ServerClass=BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
def test(HandlerClass = AuthHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
from SimpleHTTPServer import SimpleHTTPRequestHandler import BaseHTTPServer class HTTPRequestHandler(SimpleHTTPRequestHandler): extensions_map = SimpleHTTPRequestHandler.extensions_map.copy() extensions_map.update({ '.vcf': 'text/plain', }) if __name__ == '__main__': BaseHTTPServer.test(HTTPRequestHandler, BaseHTTPServer.HTTPServer)
#! /usr/bin/env python2 from SimpleHTTPServer import SimpleHTTPRequestHandler import BaseHTTPServer class CORSRequestHandler (SimpleHTTPRequestHandler): def end_headers (self): self.send_header('Access-Control-Allow-Origin', 'http://localhost:8080') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
def test(HandlerClass = googleCacheHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
def do_POST(self): if self.path == "/HELLO": print("Received HELLO, response HTTP 200") self.respond_ok("READY") elif self.path == "/TRAIN": print("Received TRAIN ... training ... response HTTP 200") self.respond_ok( ['OK', 'http://{}:{}'.format(this_ip_address, port)]) elif self.path == "/TEST": print("Received TEST ... testing ... response HTTP 200") self.respond_ok( ['OK', 'http://{}:{}'.format(this_ip_address, port)]) else: self.send_response(httplib.NOT_FOUND) if __name__ == '__main__': httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', port), ComputingEnvironmentHandler) try: print("Server starting ...") httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close() # MockComputingEnvironment.run()
import naglfar import BaseHTTPServer class HelloWorldHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): if self.path == "/": self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("Hello, world") else: self.send_error(404) if __name__ == "__main__": class ScheduledHTTPServer(naglfar.ScheduledMixIn, BaseHTTPServer.HTTPServer): pass BaseHTTPServer.test(HelloWorldHandler, ScheduledHTTPServer)
def test(HandlerClass=SimpleHTTPRequestHandler, ServerClass=BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
def _start_http_server(port): server = BaseHTTPServer.HTTPServer(('', int(port)), _fMBTwebRequestHandler) thread.start_new_thread(_run_server, (server, )) return server
return True return False def getRefs(fname): d = getDump() out = [] for otherfile in d: if 'links' in d[otherfile]: if fname in d[otherfile]['links']: out.append(otherfile) return out def scanDir(): dr = os.listdir(os.getcwd()) dr = [f for f in dr if os.path.isfile(f) and f.endswith('.md')] s = False for f in dr: if scanFile(f): s = True if s: saveDump() if __name__=="__main__": BaseHTTPServer.test(DirectoryHandler, BaseHTTPServer.HTTPServer)
def Start(port): server_address = ('', port) httpd = BaseHTTPServer.HTTPServer(server_address, StatusHandler) thread = StatusServerThread(httpd) thread.setDaemon(True) thread.start()
def test(HandlerClass=ProxyHTTPRequestHandler, ServerClass=ThreadingHTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
import BaseHTTPServer import SimpleHTTPServer import ssl import sys if __name__ == "__main__": httpd = BaseHTTPServer.HTTPServer( ('127.0.0.1', int(sys.argv[1])), SimpleHTTPServer.SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile='server.pem', server_side=True) httpd.serve_forever()
def main(HandlerClass = HiScoresHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
def __init__(self, port): """Constructs an HTTP Server listening at the provided port.""" address = ('localhost', port) self.httpd = BaseHTTPServer.HTTPServer(address, Server.RegistrationHandler)
#!/usr/bin/env python import BaseHTTPServer class EchoHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): response = '%s %s %s\n%s' % \ (self.command, self.path, self.request_version, self.headers) self.send_response(200) self.send_header('Content-Type', 'text/plain') self.end_headers() self.wfile.write(response) def do_POST(self): self.do_GET() self.wfile.write('\n') length = int(self.headers.getheader('Content-Length')) self.wfile.write(self.rfile.read(length)) BaseHTTPServer.test(EchoHTTPRequestHandler)
return self.extensions_map[ext] ext = ext.lower() if ext in self.extensions_map: return self.extensions_map[ext] else: return self.extensions_map[''] if not mimetypes.inited: mimetypes.init() # try to read system mime.types extensions_map = mimetypes.types_map.copy() extensions_map.update({ '': 'application/octet-stream', # Default '.py': 'text/plain', '.c': 'text/plain', '.h': 'text/plain', '.mp4': 'video/mp4', '.ogg': 'video/ogg', }) if __name__ == '__main__': server_address = ('localhost', 2424) RangeHTTPRequestHandler.protocol_version = "HTTP/1.0" httpd = BaseHTTPServer.HTTPServer(server_address, RangeHTTPRequestHandler) sa = httpd.socket.getsockname() print("Serving HTTP on", sa[0], "port", sa[1], "...") while keep_alive: httpd.handle_request()
def runServer(HandlerClass = BitsHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
def review(ui, repo, *paths, **opts): ''' Uploads a review to https://codereview.adblockplus.org/ or updates an existing review request. This will always send mails for new reviews, when updating a review mails will only be sent if a message is given. ''' args = ['--oauth2', '--server', SERVER] if ui.debugflag: args.append('--noisy') elif ui.verbose: args.append('--verbose') elif ui.quiet: args.append('--quiet') if not opts.get('issue') or opts.get('message'): args.append('--send_mail') if opts.get('revision') and opts.get('change'): raise error.Abort( 'Ambiguous revision range, only one of --revision and --change can be specified.' ) if opts.get('change'): rev = repo[opts['change']] args.extend(['--rev', '{}:{}'.format(rev.parents()[0], rev)]) elif opts.get('revision'): args.extend(['--rev', opts['revision']]) else: raise error.Abort( 'What should be reviewed? Either --revision or --change is required.' ) if not opts.get('issue'): # New issue, make sure title and message are set if not opts.get('title') and opts.get('change'): opts['title'] = repo[opts['change']].description() if not opts.get('title'): opts['title'] = ui.prompt('New review title: ', '') if not opts['title'].strip(): raise error.Abort('No review title given.') if not opts.get('message'): opts['message'] = opts['title'] path = (ui.config('paths', 'default-push') or ui.config('paths', 'default') or '') match = re.search(r'^(?:https://|ssh://hg@)(.*)', path) if match: opts['base_url'] = 'https://' + match.group(1) # Make sure there is at least one reviewer if not opts.get('reviewers'): opts['reviewers'] = ui.prompt('Reviewers (comma-separated): ', '') if not opts['reviewers'].strip(): raise error.Abort('No reviewers given.') for opt in ('reviewers', 'cc'): if opts.get(opt): users = [ u if '@' in u else u + '@adblockplus.org' for u in re.split(r'\s*,\s*', opts[opt]) ] opts[opt] = ','.join(users) for opt in ('issue', 'title', 'message', 'reviewers', 'cc', 'base_url'): if opts.get(opt, ''): args.extend(['--' + opt, opts[opt]]) for opt in ('private', 'assume_yes', 'print_diffs'): if opts.get(opt, False): args.append('--' + opt) args.extend(paths) upload_path = ui.config('review', 'uploadtool_path', os.path.join('~', '.hgreview_upload.py')) upload_path = os.path.expanduser(upload_path) if not os.path.exists(upload_path): ui.status('Downloading {0} to {1}.\n'.format(UPLOADTOOL_URL, upload_path)) urllib.urlretrieve(UPLOADTOOL_URL, upload_path) # Find an available port for our local server issue = None class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/javascript') self.end_headers() self.wfile.write('location.href = "{0}";'.format(SERVER + '/' + issue)) def log_message(*args, **kwargs): pass for port in range(54770, 54780): try: server = BaseHTTPServer.HTTPServer(('localhost', port), RequestHandler) break except socket.error: pass # Modify upload tool's auth response in order to redirect to the issue scope = {} execfile(upload_path, scope) if server: scope['AUTH_HANDLER_RESPONSE'] = '''\ <html> <head> <title>Authentication Status</title> <script> window.onload = function() { setInterval(function() { var script = document.createElement("script"); script.src = "http://localhost:%s/?" + (new Date().getTime()); document.body.appendChild(script); }, 1000) } </script> </head> <body> <p> The authentication flow has completed. This page will redirect to your review shortly. </p> </body> </html> ''' % port # Run the upload tool issue, patchset = scope['RealMain']([upload_path] + args) # Wait for the page to check in and retrieve issue URL if server: server.handle_request()
fo.close() print "created src/sketch.ino" # invoke ino to build/upload # skip_lib_includes is used to avoid "line too long" errors with IDE 1.5.8+ rc = os.system("ino build --skip_lib_includes") # 512 probably means invalid option (skip_lib_includes) if rc == 512: print "ino build returned " + `rc` + " - trying again without skip_lib_includes" rc = os.system("ino build") if not rc == 0: print "ino build returned " + `rc` self.send_response(400) else: rc = os.system("ino upload") if not rc == 0: print "ino upload returned " + `rc` self.send_response(500) else: self.send_response(200) if __name__ == '__main__': print "running local web server at 127.0.0.1:8080..." server = BaseHTTPServer.HTTPServer(("127.0.0.1", 8080), Handler) server.pages = {} server.serve_forever() Status API Training Shop Blog About Pricing
def test(HandlerClass = ProxyHTTPRequestHandler, ServerClass = ThreadingHTTPServer): ProxyHTTPRequestHandler.basic_auth_handler.set_users({'jenny':'supersecret'}) ProxyHTTPRequestHandler.basic_auth_handler.set_realm('lugh.localdomain') BaseHTTPServer.test(HandlerClass, ServerClass)
# https://www.piware.de/2011/01/creating-an-https-server-in-python/ # make self-signed cert: # openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes import argparse import BaseHTTPServer import SimpleHTTPServer import ssl class djHTTPServer(SimpleHTTPServer.SimpleHTTPRequestHandler): pass if '__main__' == __name__: parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', required=True, help='listen port') parser.add_argument('-s', '--ssl', action='store_true', help='SSL') parser.add_argument('-v', '--verbose', action='store_true', help='be verbose') args = parser.parse_args() httpd = BaseHTTPServer.HTTPServer(('', int(args.port)), djHTTPServer) if args.ssl: httpd.socket = ssl.wrap_socket(httpd.socket, certfile='localhost.pem', server_side=True) httpd.serve_forever()
#!/usr/bin/env python import SimpleHTTPServer, BaseHTTPServer, os os.chdir('../games') try: print "Server starting. Visit http://localhost:8000/ in your browser." BaseHTTPServer.test( SimpleHTTPServer.SimpleHTTPRequestHandler, BaseHTTPServer.HTTPServer ) except KeyboardInterrupt: print
def test(HandlerClass=OptimalRoutingServer, ServerClass=BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
def send_error(self, code, message = None): import jambe.libs.theme """ Override BaseHTTPServer.send_error() """ try: short, long = self.responses[code] except KeyError: short, long = '???', '???' if message is None: message = short explain = long self.log_error("code %d, message %s", code, message) # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201) content = self._jambe.Theme.render_template('error.html', {'code': code, 'message': BaseHTTPServer._quote_html(message), 'explain': explain}) headers = {'Content-Type': self.error_content_type, 'Connection': 'close'} self.send(content = content, headers = headers, code = code, message = message)
returnDict["message"] = returned else: serverList = {} for server in Servers.values(): if server.connectedPlayers is not server.maxPlayers: serverList[server.name] = { 'name': server.name, 'ip': server.ipPort, 'maxPlayers': server.maxPlayers, 'connectedPlayers': server.connectedPlayers, "players": server.players } returned = "Returned List of not-full Servers!" print returned returnDict["ok"] = True returnDict["servers"] = serverList returnDict["message"] = returned s.send_response(200) s.send_header("CONTENT-TYPE", "Application/JSON") s.end_headers() s.wfile.write(json.dumps(returnDict)) handler = MSHandler httpd = BaseHTTPServer.HTTPServer(('localhost', 8000), handler) httpd.serve_forever()
environ={"REQUEST_METHOD": "POST"} ) env = {} for item in form.list: env[item.name] = item.value for request_path, php_file in self.dynamics.items(): if self.path.startswith(request_path): proc = subprocess.Popen(["php", php_file], env=env, stdout=subprocess.PIPE) output = proc.communicate()[0] print "Input: " + env.__str__() print "Output: " + output self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", output.__len__()) self.end_headers() self.wfile.write(output) break self.do_GET() class ThreadingSimpleServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass BaseHTTPServer.test(MyHandler, ThreadingSimpleServer)
# simple web app to illustrate kubernetes concepts class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() client = str(self.headers.get("X-Forwarded-For", "n/a")) + " - " + str( self.client_address[0]) response = b'[' + datetime.datetime.now().strftime( "%Y%m%d-%H%M%S.%f" ) + ']' + b' key=' + key + b' host=' + hostname + b' - Hello ' + client + ' \n' self.wfile.write(response) print("==> " + response) if sys.argv[2:]: port = int(sys.argv[1]) key = str(sys.argv[2]) else: port = int(os.getenv('CHECKIT_PORT', 8080)) key = os.getenv('CHECKIT_KEY', "n/a") server_address = ('0.0.0.0', port) hostname = socket.gethostname() if len(hostname) > 5: hostname = hostname[-5:] print "starting with..." + str( server_address) + " key=" + key + " on " + hostname httpd = BaseHTTPServer.HTTPServer(server_address, MyRequestHandler) httpd.serve_forever()
def test(HandlerClass = HandlerWithPost, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
'http://axschema.org/namePerson/first') required.append('firstname') if args.lastname: request.addExtensionArg('http://openid.net/srv/ax/1.0', 'type.lastname', 'http://axschema.org/namePerson/last') required.append('lastname') if args.country: request.addExtensionArg('http://openid.net/srv/ax/1.0', 'type.country', 'http://axschema.org/contact/country/home') required.append('country') if args.language: request.addExtensionArg('http://openid.net/srv/ax/1.0', 'type.language', 'http://axschema.org/pref/language') required.append('language') if required: request.addExtensionArg('http://openid.net/srv/ax/1.0', 'required', ','.join(required)) url = request.redirectURL(realm, return_to, immediate=False) if not url: raise Exception('Authenticate url is None') print 'Start Server, Please wait ...' httpd = BaseHTTPServer.HTTPServer(('', port), RequestHandler) webbrowser.open(url) httpd.handle_request() httpd.server_close()
count += 1 (ins, _, exs) = select.select(iw, ow, iw, 3) if exs: break if ins: for i in ins: if i is soc: out = self.connection else: out = soc data = i.recv(8192) if data: out.send(data) count = 0 else: print "..", count, if count == max_idling: break do_HEAD = do_GET do_POST = do_GET do_PUT = do_GET do_DELETE= do_GET class ThreadingHTTPServer (SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass if __name__ == '__main__': from sys import argv if argv[1:] and argv[1] in ('-h', '--help'): print argv[0], "[port]" BaseHTTPServer.test(ProxyHandler, ThreadingHTTPServer)
<p>{msg}</p> </body> </html> """ def do_GET(self): try: self.full_path = os.getcwd() + self.path for case in self.Cases: if case.test(self): case.act(self) break except Exception as msg: self.handle_error(msg) def handle_error(self, msg): content = self.Error_Page.format(path=self.path, msg=msg) self.send_content(content, 404) # 发送数据到客户端 def send_content(self, content, status=200): self.send_response(status) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content) if __name__ == '__main__': serverAddress = ('', 8888) server = BaseHTTPServer.HTTPServer(serverAddress, RequestHandler) server.serve_forever()
def test(HandlerClass = SimpleHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
__author__ = 'nancy' import CGIHTTPServer import BaseHTTPServer class Handler(CGIHTTPServer.CGIHTTPRequestHandler): cgi_directories = ["/cgi"] PORT = 8000 httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever()