本文整理汇总了Python中http.server.serve_forever方法的典型用法代码示例。如果您正苦于以下问题:Python server.serve_forever方法的具体用法?Python server.serve_forever怎么用?Python server.serve_forever使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http.server
的用法示例。
在下文中一共展示了server.serve_forever方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def setUp(self):
RegisterPath("^{0}$".format(self.test_resource[1:]), self.handler_class.__name__)(self._test_resource_handler)
self.server = self.server_class(self.handler_class, **self._server_kwargs)
self.assertTrue(isinstance(self.server, AdvancedHTTPServer))
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.daemon = True
self.server_thread.start()
self.assertTrue(self.server_thread.is_alive())
self.shutdown_requested = False
if len(self.server_address) == 3 and self.server_address[2]:
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
self.http_connection = http.client.HTTPSConnection(self.server_address[0], self.server_address[1], context=context)
else:
self.http_connection = http.client.HTTPConnection(self.server_address[0], self.server_address[1])
self.http_connection.connect()
示例2: main
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def main():
try:
server = build_server_from_argparser()
except ImportError:
server = AdvancedHTTPServer(RequestHandler, use_threads=False)
server.serve_files_root = '.'
server.serve_files_root = (server.serve_files_root or '.')
server.serve_files = True
try:
server.serve_forever()
except KeyboardInterrupt:
pass
server.shutdown()
logging.shutdown()
return 0
示例3: get_wsgi_server
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def get_wsgi_server(app):
if hasattr(app, '__webview_url'):
# It's already been spun up and is running
return app.__webview_url
port = _get_random_port()
server = wsgiref.simple_server.make_server(
'localhost', port, app, server_class=ThreadingWSGIServer,
handler_class=WSGIRequestHandler11,
)
t = threading.Thread(target=server.serve_forever)
t.daemon = True
t.start()
app.__webview_url = 'http://localhost:{0}/'.format(port)
logger.debug('HTTP server for {!r} started on {}'.format(app, app.__webview_url))
return app.__webview_url
示例4: serve_forever
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def serve_forever(self, fork=False):
"""
Start handling requests. This method must be called and does not
return unless the :py:meth:`.shutdown` method is called from
another thread.
:param bool fork: Whether to fork or not before serving content.
:return: The child processes PID if *fork* is set to True.
:rtype: int
"""
if fork:
if not hasattr(os, 'fork'):
raise OSError('os.fork is not available')
child_pid = os.fork()
if child_pid != 0:
self.logger.info('forked child process: ' + str(child_pid))
return child_pid
self.__server_thread = threading.current_thread()
self.__wakeup_fd = WakeupFd()
self.__is_shutdown.clear()
self.__should_stop.clear()
self.__is_running.set()
while not self.__should_stop.is_set():
try:
self._serve_ready()
except socket.error:
self.logger.warning('encountered socket error, stopping server')
self.__should_stop.set()
self.__is_shutdown.set()
self.__is_running.clear()
return 0
示例5: start_server
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def start_server(socket, projectname, xmlfilename: str) -> None:
"""Start the *HydPy* server using the given socket.
The folder with the given `projectname` must be available within the
current working directory. The XML configuration file must be placed
within the project folder unless `xmlfilename` is an absolute file path.
The XML configuration file must be valid concerning the schema file
`HydPyConfigMultipleRuns.xsd` (see method |ServerState.initialise|
for further information).
Note that function |start_server| tries to read the "mime types" from
a dictionary stored in the file `mimetypes.txt` available in subpackage
`conf`, and passes it as attribute `extension_map` to class |HydPyServer|.
The reason is to avoid the long computation time of function
|mimetypes.init| of module |mimetypes|, usually called when defining
class `BaseHTTPRequestHandler` of module `http.server`. If file
`mimetypes.txt` does not exist or does not work for some reasons,
|start_server| calls |mimetypes.init| as usual, (over)writes
`mimetypes.txt`, and tries to proceed as expected.
"""
filepath = os.path.join(conf.__path__[0], 'mimetypes.txt')
try:
with open(filepath) as file_:
dict_ = eval(open(file_.read()))
except BaseException:
mimetypes.init()
dict_ = mimetypes.types_map.copy()
dict_.update({
'': 'application/octet-stream',
'.py': 'text/plain',
'.c': 'text/plain',
'.h': 'text/plain',
})
with open(filepath, 'w') as file_:
file_.write(str(dict_))
HydPyServer.extensions_map = dict_
state.initialise(projectname, xmlfilename)
server = http.server.HTTPServer(('', int(socket)), HydPyServer)
server.serve_forever()
示例6: http_wait_server
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def http_wait_server():
# Simple http handler which waits 10 seconds before responding
class WaitHanlder(http.server.BaseHTTPRequestHandler):
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_GET(self):
time.sleep(10)
try:
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>Test wait handler</title></head>"
"<body><p>Test Wait</p></body></html>", 'utf-8'))
self.flush_headers()
except BrokenPipeError: # ignore broken pipe as socket might have been closed
pass
# disable logging
def log_message(self, format, *args):
pass
with http.server.ThreadingHTTPServer(('', 10888), WaitHanlder) as server:
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
yield
server.shutdown()
server_thread.join()
# Some web servers can block the connection after the http is sent
# In this case chromium will hang. An example for this is:
# curl -v -H 'user-agent: HeadlessChrome' --max-time 10 "http://www.grainger.com/" # disable-secrets-detection
# This tests access a server which waits for 10 seconds and makes sure we timeout
示例7: setUpClass
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def setUpClass(cls):
TestDownloaderBase.setUpClass()
cls.downloader = downloader.find("http")(cls.job)
port = 8088
cls.address = "http://127.0.0.1:{}".format(port)
cls._jpg = cls.address + "/image.jpg"
cls._png = cls.address + "/image.png"
cls._gif = cls.address + "/image.gif"
server = http.server.HTTPServer(("", port), HttpRequestHandler)
threading.Thread(target=server.serve_forever, daemon=True).start()
示例8: main
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def main(args=None):
"""Runs a basic http server to show healthcheck functionality."""
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--port",
help="Unused port to run the tiny"
" http server on (or zero to select a"
" random unused port)",
type=positive_int, required=True)
args = parser.parse_args(args=args)
server = create_server(args.port)
print("Serving at port: %s" % server.server_address[1])
server.serve_forever()
示例9: _http_python3
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def _http_python3(self, listen_ssl=False):
"""Listen for HTTP connections with Python 3."""
handler = DeenHTTPRequestHandler
os.chdir(self.serving_directory)
try:
with socketserver.TCPServer(self.listen_socket, handler) as httpd:
if listen_ssl:
# The certificate chain and private key need to
# be available as actual files that can be opened
# with fopen(3).
with tempfile.TemporaryDirectory() as tmpdirname:
cert_chain = tmpdirname + '/cert_chain.pem'
server_key = tmpdirname + '/server_key.pem'
with open(cert_chain, 'wb') as f:
f.write(self.server_cert_pem)
with open(server_key, 'wb') as f:
f.write(self.server_key_pem)
httpd.socket = ssl.wrap_socket(httpd.socket,
certfile=cert_chain,
keyfile=server_key,
server_side=True)
message = 'Serving HTTP at port ' + str(self.listen_port)
if listen_ssl:
message += ' (SSL)'
print(message)
try:
httpd.serve_forever()
except KeyboardInterrupt:
httpd.socket.close()
except OSError as e:
self.error = e
self.log.error(self.error)
self.log.debug(self.error, exc_info=True)
示例10: ssltlsServer
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def ssltlsServer(victims, poodleManager):
print("Starting SSL/TLS server on {}:{} forwarding to {}:{}".format(args.listen_host, args.listen_port_tls, args.target_host, args.target_port))
server = SSLTLSProxy((args.listen_host, int(args.listen_port_tls)), SSLTLSHandler)
server.victims = victims
server.poodleManager = poodleManager
try:
server.serve_forever()
except KeyboardInterrupt:
print("Shutdown of SSL/TLS server on user request")
示例11: httpServer
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def httpServer(victims, poodleManager):
print("Starting HTTP server on {}:{} generating requests to {}".format(args.listen_host, args.listen_port_http, args.targetURL))
server = http.server.HTTPServer((args.listen_host, int(args.listen_port_http)), PoodleHTTPRequestHandler)
server.victims = victims
server.poodleManager = poodleManager
try:
server.serve_forever()
except KeyboardInterrupt:
print("Shutdown of HTTP server on user request")
示例12: start_smart_module_server
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def start_smart_module_server(download_url):
"""Serve documentation and module requests at the same URL."""
# pylint:disable=g-import-not-at-top
if sys.version_info[0] == 2:
import BaseHTTPServer
import SimpleHTTPServer
import urlparse
class HTTPServerV6(BaseHTTPServer.HTTPServer):
address_family = socket.AF_INET6
class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
parsed_url = urlparse.urlparse(self.path)
qs = urlparse.parse_qs(parsed_url.query)
if qs["tf-hub-format"][0] == "compressed":
_do_redirect(self, download_url)
else:
_do_documentation(self)
server = HTTPServerV6(("", 0), RequestHandler)
server_port = server.server_port
else:
import http.server
import socketserver
import urllib
class TCPServerV6(socketserver.TCPServer):
address_family = socket.AF_INET6
class RequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
parsed_url = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed_url.query)
if qs["tf-hub-format"][0] == "compressed":
_do_redirect(self, download_url)
else:
_do_documentation(self)
server = TCPServerV6(("", 0), RequestHandler)
_, server_port, _, _ = server.server_address
# pylint:disable=g-import-not-at-top
thread = threading.Thread(target=server.serve_forever)
thread.daemon = True
thread.start()
return server_port
示例13: start_http_server
# 需要导入模块: from http import server [as 别名]
# 或者: from http.server import serve_forever [as 别名]
def start_http_server(redirect=None):
"""Returns the port of the newly started HTTP server."""
# Start HTTP server to serve TAR files.
# pylint:disable=g-import-not-at-top
if sys.version_info[0] == 2:
import BaseHTTPServer
import SimpleHTTPServer
class HTTPServerV6(BaseHTTPServer.HTTPServer):
address_family = socket.AF_INET6
class RedirectHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
_do_redirect(self, redirect)
server = HTTPServerV6(("", 0), RedirectHandler if redirect else
SimpleHTTPServer.SimpleHTTPRequestHandler)
server_port = server.server_port
else:
import http.server
import socketserver
class TCPServerV6(socketserver.TCPServer):
address_family = socket.AF_INET6
class RedirectHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
_do_redirect(self, redirect)
server = TCPServerV6(("", 0), RedirectHandler if redirect else
http.server.SimpleHTTPRequestHandler)
_, server_port, _, _ = server.server_address
# pylint:disable=g-import-not-at-top
thread = threading.Thread(target=server.serve_forever)
thread.daemon = True
thread.start()
return server_port