本文整理汇总了Python中http.server.SimpleHTTPRequestHandler方法的典型用法代码示例。如果您正苦于以下问题:Python server.SimpleHTTPRequestHandler方法的具体用法?Python server.SimpleHTTPRequestHandler怎么用?Python server.SimpleHTTPRequestHandler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http.server
的用法示例。
在下文中一共展示了server.SimpleHTTPRequestHandler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: serve
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def serve():
"""
A quick server to preview a built site with translations.
For development, prefer the command live (or just mkdocs serve).
This is here only to preview a site with translations already built.
Make sure you run the build-all command first.
"""
typer.echo("Warning: this is a very simple server.")
typer.echo("For development, use the command live instead.")
typer.echo("This is here only to preview a site with translations already built.")
typer.echo("Make sure you run the build-all command first.")
os.chdir("site")
server_address = ("", 8008)
server = HTTPServer(server_address, SimpleHTTPRequestHandler)
typer.echo(f"Serving at: http://127.0.0.1:8008")
server.serve_forever()
示例2: http_server
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def http_server():
timeout = 10
class RequestHandler(SimpleHTTPRequestHandler):
protocol_version = "HTTP/1.0"
def log_message(self, *args):
pass
with HTTPServer((Address, Port), RequestHandler) as httpd:
thread = Thread(target=httpd.serve_forever, daemon=True)
thread.start()
c = HTTPConnection(Address, Port, timeout=timeout)
c.request("GET", "/", "")
assert c.getresponse().status == 200
try:
yield httpd
finally:
httpd.shutdown()
thread.join(timeout=timeout)
示例3: is_gzip_accepted
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def is_gzip_accepted(self):
accepted = set()
for header in self.headers.get_all("Accept-Encoding"):
# Then, you are allowed to specify a comma separated list of
# acceptable encodings. You are also allowed to specify
# 'encoding;q=XXX' to specify what encodings you would prefer.
# We'll allow it to be set, but just ignore it.
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
accepted.update(
encoding.strip().split(";", 1)[0]
for encoding in header.split(",")
)
return "gzip" in accepted
# This is a copy & paste and minor modification of
# SimpleHTTPRequestHandler's send_head code. Because to support
# Content-Encoding gzip, we have to change what headers get returned (as it
# affects Content-Length headers.
示例4: run
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def run(user, port=4242):
"""
Build a temporary directory with a visualization and serve it over HTTP.
Examples
--------
>>> bandicoot.visualization.run(U)
Successfully exported the visualization to /tmp/tmpsIyncS
Serving bandicoot visualization at http://0.0.0.0:4242
"""
owd = os.getcwd()
dir = export(user)
os.chdir(dir)
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
try:
httpd = SocketServer.TCPServer(("", port), Handler)
print("Serving bandicoot visualization at http://0.0.0.0:%i" % port)
httpd.serve_forever()
except KeyboardInterrupt:
print("^C received, shutting down the web server")
httpd.server_close()
finally:
os.chdir(owd)
示例5: __enter__
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def __enter__(self):
class ServerHandler(SimpleHTTPRequestHandler):
def do_GET(_self):
_self.protocol_version = 'HTTP/1.1'
self._headers = _self.headers
self._url = _self.path
_self.send_response(200)
_self.send_header("Content-type", "application/json")
_self.end_headers()
_self.wfile.write(b"{}")
self.server = HTTPServer(("", 51352), ServerHandler)
def thread_func():
self.server.serve_forever()
thread = threading.Thread(target=thread_func)
thread.start()
return self
示例6: run
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def run(self, open_immediately, port):
'''
Serves the `www` directory.
Args:
open_immediately: Whether to open the web browser immediately
port: The port at which to serve the graph
'''
os.chdir(self.directory)
handler = http.SimpleHTTPRequestHandler
handler.extensions_map.update({
'.webapp': 'application/x-web-app-manifest+json',
})
server = socketserver.TCPServer(('', port), handler)
server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
address = 'http://localhost:{0}/graph.html'.format(port)
log.info('Serving at %s', address)
if open_immediately:
log.debug('Opening webbrowser')
webbrowser.open(address)
server.serve_forever()
示例7: tmpdir_server
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def tmpdir_server(tmpdir):
if sys.version_info >= (3, 7):
Handler = partial(SimpleHTTPRequestHandler, directory=str(tmpdir))
from http.server import ThreadingHTTPServer
else:
# unfortunately SimpleHTTPRequestHandler doesn't accept the directory arg in python3.6
# so we have to hack it like this
import os
class Handler(SimpleHTTPRequestHandler):
def translate_path(self, path):
# get the path from cwd
path = super().translate_path(path)
# get the relative path
relpath = os.path.relpath(path, os.getcwd())
# return the full path from root_dir
return os.path.join(str(tmpdir), relpath)
# ThreadingHTTPServer was added in 3.7, so we need to define it ourselves
from socketserver import ThreadingMixIn
from http.server import HTTPServer
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
with ThreadingHTTPServer(('localhost', 0), Handler) as server:
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
yield server.server_address
server.shutdown()
示例8: __init__
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler):
threading.Thread.__init__(self)
self.handler = handler
self.test = test
示例9: __init__
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def __init__(self, profile_json, *args, **kwargs):
self._profile_json = profile_json
self.uri_map = {
'/': self._handle_root,
'/profile': self._handle_profile,
}
# Since this class is old-style - call parent method directly.
server.SimpleHTTPRequestHandler.__init__(
self, *args, **kwargs)
示例10: handle_one_request
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def handle_one_request(self):
try:
httpserver.SimpleHTTPRequestHandler.handle_one_request(self)
except socket.error as e:
dprint("Socket error: %s" % e)
if not hasattr(self, "_host_disconnected"):
self._host_disconnected = 1
dprint("Host disconnected")
elif self._host_disconnected < State.max_disconnect:
self._host_disconnected += 1
dprint("Host disconnected: %d" % self._host_disconnected)
else:
dprint("Closed connection to avoid infinite loop")
self.close_connection = True
示例11: main
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def main(
*additional_dist_formats: Format,
verbosity: int = 0,
local: bool = False,
serve: bool = False
) -> None:
pex_output_file = DIST_DIR / 'pex'
print(f'Building Pex PEX to `{pex_output_file}` ...')
build_pex_pex(pex_output_file, local, verbosity)
git_rev = describe_git_rev()
sha256, size = describe_file(pex_output_file)
print(f'Built Pex PEX @ {git_rev}:')
print(f'sha256: {sha256}')
print(f' size: {size}')
if additional_dist_formats:
print(f'Building additional distribution formats to `{DIST_DIR}`: '
f'{", ".join(f"{i + 1}.) {fmt}" for i, fmt in enumerate(additional_dist_formats))} ...')
build_pex_dists(*additional_dist_formats, verbose=verbosity > 0)
print('Built:')
for root, _, files in os.walk(DIST_DIR):
root_path = Path(root)
for f in files:
dist_path = (root_path / f)
if dist_path != pex_output_file:
print(f' {dist_path}')
if serve:
server = HTTPServer(('', 0), SimpleHTTPRequestHandler)
host, port = server.server_address
print(f'Serving Pex distributions from `{DIST_DIR}` at http://{host}:{port} ...')
os.chdir(DIST_DIR)
try:
server.serve_forever()
except KeyboardInterrupt:
print(f'Server shut down in response to keyboard interrupt.')
示例12: main
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def main():
PORT = free_port()
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
# There is a bug that you have to refresh web page so you can see htmlreport
# Even I tried to use threading to delay webbrowser open tab
# but still need to refresh to let report show up.
# I guess this is SimpleHTTPServer bug
webbrowser.open('http://127.0.0.1:%d' % PORT, new=2)
print("serving at port", PORT)
httpd.serve_forever(0.1)
示例13: start_impl
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def start_impl(self):
os.chdir(self.root_path)
class ReuseAddressTCPServer(TCPServer):
allow_reuse_address = True
httpd = ReuseAddressTCPServer(
('0.0.0.0', self.port), SimpleHTTPRequestHandler)
httpd.serve_forever()
示例14: _make_handler
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def _make_handler(external_env):
class Handler(SimpleHTTPRequestHandler):
def do_POST(self):
content_len = int(self.headers.get("Content-Length"), 0)
raw_body = self.rfile.read(content_len)
parsed_input = pickle.loads(raw_body)
try:
response = self.execute_command(parsed_input)
self.send_response(200)
self.end_headers()
self.wfile.write(pickle.dumps(response))
except Exception:
self.send_error(500, traceback.format_exc())
def execute_command(self, args):
command = args["command"]
response = {}
if command == PolicyClient.START_EPISODE:
response["episode_id"] = external_env.start_episode(
args["episode_id"], args["training_enabled"])
elif command == PolicyClient.GET_ACTION:
response["action"] = external_env.get_action(
args["episode_id"], args["observation"])
elif command == PolicyClient.LOG_ACTION:
external_env.log_action(args["episode_id"],
args["observation"], args["action"])
elif command == PolicyClient.LOG_RETURNS:
external_env.log_returns(args["episode_id"], args["reward"],
args["info"])
elif command == PolicyClient.END_EPISODE:
external_env.end_episode(args["episode_id"],
args["observation"])
else:
raise Exception("Unknown command: {}".format(command))
return response
return Handler
示例15: server_demo
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 别名]
def server_demo():
running = True
httpd = HTTPServer(('localhost', 8080), SimpleHTTPRequestHandler)
while running:
httpd.handle_request()
httpd.shutdown()