本文整理匯總了Python中http.server.HTTPServer方法的典型用法代碼示例。如果您正苦於以下問題:Python server.HTTPServer方法的具體用法?Python server.HTTPServer怎麽用?Python server.HTTPServer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類http.server
的用法示例。
在下文中一共展示了server.HTTPServer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: itn_handler
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def itn_handler(host, port): # type: (str, int) -> Iterator[Queue]
"""
Usage::
with itn_handler(ITN_HOST, ITN_PORT) as itn_queue:
# ...complete PayFast payment...
itn_data = itn_queue.get(timeout=2)
"""
server_address = (host, port)
http_server = HTTPServer(server_address, PayFastITNHandler)
http_server.itn_queue = Queue() # type: ignore
executor = ThreadPoolExecutor(max_workers=1)
executor.submit(http_server.serve_forever)
try:
yield http_server.itn_queue # type: ignore
finally:
http_server.shutdown()
示例2: _start_server
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def _start_server(self):
# start a server listening for messages
self.logger.info(
"Starting http server for HttpCommunicationLayer " "on %s", self.address
)
try:
_, port = self._address
self.httpd = HTTPServer(("0.0.0.0", port), MPCHttpHandler)
except OSError:
self.logger.error(
"Cannot bind http server on adress {}".format(self.address)
)
raise
self.httpd.comm = self
t = Thread(name="http_thread", target=self.httpd.serve_forever, daemon=True)
t.start()
示例3: serve
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [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()
示例4: http_server
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def http_server(port=8000, cwd=None, terminate_callable=None):
http = HTTPServer(('', port), HTTPRequestHandler)
http.timeout = 1
if cwd is None:
cwd = os.getcwd()
http.cwd = cwd
while True:
if terminate_callable is not None:
terminate = terminate_callable()
else:
terminate = False
if terminate:
break
http.handle_request()
示例5: SetupPrometheusEndpointOnPort
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def SetupPrometheusEndpointOnPort(port, addr=""):
"""Exports Prometheus metrics on an HTTPServer running in its own thread.
The server runs on the given port and is by default listenning on
all interfaces. This HTTPServer is fully independent of Django and
its stack. This offers the advantage that even if Django becomes
unable to respond, the HTTPServer will continue to function and
export metrics. However, this also means that the features
offered by Django (like middlewares or WSGI) can't be used.
Now here's the really weird part. When Django runs with the
auto-reloader enabled (which is the default, you can disable it
with `manage.py runserver --noreload`), it forks and executes
manage.py twice. That's wasteful but usually OK. It starts being a
problem when you try to open a port, like we do. We can detect
that we're running under an autoreloader through the presence of
the RUN_MAIN environment variable, so we abort if we're trying to
export under an autoreloader and trying to open a port.
"""
assert os.environ.get("RUN_MAIN") != "true", (
"The thread-based exporter can't be safely used when django's "
"autoreloader is active. Use the URL exporter, or start django "
"with --noreload. See documentation/exports.md."
)
prometheus_client.start_http_server(port, addr=addr)
示例6: run_on
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def run_on(ip, port):
"""
Starts the HTTP server in the given port
:param port: port to run the http server
:return: void
"""
print("Starting a server on port {0}. Use CNTRL+C to stop the server.".format(port))
server_address = (ip, port)
try:
httpd = HTTPServer(server_address, SparrestHandler)
httpd.serve_forever()
except OSError as e:
if e.errno == 48: # port already in use
print("ERROR: The port {0} is already used by another process.".format(port))
else:
raise OSError
except KeyboardInterrupt as interrupt:
print("Server stopped. Bye bye!")
示例7: run
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def run(self):
server = self
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
"""Serves the GEDCOM file and referenced files."""
# Take the file map in a thread-safe way.
with server.lock:
file_map = server.file_map
# Return 404 if a file is not known.
if not self.path in file_map:
self.send_response(404)
return
# Respond with the file contents.
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', 'https://pewu.github.io')
self.end_headers()
content = open(file_map[self.path], 'rb').read()
self.wfile.write(content)
# Bind to the local address only.
server_address = ('127.0.0.1', self.port)
httpd = HTTPServer(server_address, Handler)
httpd.serve_forever()
示例8: receive_token
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def receive_token() -> str:
"""
Starts an HTTP server to receive the SSO token from browser.
It waits till a token was received.
"""
server_address = ('localhost', 80)
try:
httpd = HTTPServer(server_address, TransferServer)
except PermissionError:
Log.error('Permission denied: Please start the' +
' downloader once with administrator rights, so that it' +
' can wait on port 80 for the token.')
exit(1)
extracted_token = None
while extracted_token is None:
httpd.handle_request()
extracted_token = extract_token(TransferServer.received_token)
httpd.server_close()
return extracted_token
示例9: interactive_web
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def interactive_web(opt, parser):
SHARED['opt'] = parser.opt
SHARED['opt']['task'] = 'parlai.agents.local_human.local_human:LocalHumanAgent'
# Create model and assign it to the specified task
agent = create_agent(SHARED.get('opt'), requireModelExists=True)
SHARED['agent'] = agent
SHARED['world'] = create_task(SHARED.get('opt'), SHARED['agent'])
# show args after loading model
parser.opt = agent.opt
parser.print_args()
MyHandler.protocol_version = 'HTTP/1.0'
httpd = HTTPServer((opt['host'], opt['port']), MyHandler)
logging.info('http://{}:{}/'.format(opt['host'], opt['port']))
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
示例10: http_server
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [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)
示例11: main
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def main():
try:
server = HTTPServer(('', 80), MyHandler)
print('Welcome to the machine...')
print('Press ^C once or twice to quit.')
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server')
server.socket.close()
示例12: run
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def run(server_class=HTTPServer, handler_class=S, port=8765):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print('服務器已啟動 http://localhost:{}'.format(port))
httpd.serve_forever()
示例13: start
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def start(port=3636):
global __isstart
if __isstart: return
httpd = HTTPServer(('127.0.0.1', port), MyRequestHandler)
httpd.serve_forever() #設置一直監聽並接收請求
__isstart = True
示例14: _start
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def _start(self):
ip = get_ip()
logger.info("ProgressServer: IP address is: {}".format(ip))
RequestHandlerClass = make_request_handler_class(self.app, ip)
self.myServer = HTTPServer(("", self.port), RequestHandlerClass)
logger.info("ProgressServer: Web Server Starting - %s:%s" % ("", self.port))
try:
self.myServer.serve_forever()
except Exception:
logger.warn('ProgressServer: Exception: {}'.format(traceback.format_exc()))
finally:
self.myServer.server_close()
logger.info("ProgressServer: Web Server Stopping - %s:%s" % ("", self.port))
self.myServer = None
示例15: start_ws
# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import HTTPServer [as 別名]
def start_ws():
print('[+] Webserver listening on', BIND_WEBSERVER)
server = HTTPServer(BIND_WEBSERVER, RequestHandler)
try:
t = Thread(target=server.serve_forever)
t.daemon = True
t.start()
except KeyboardInterrupt:
server.shutdown()