當前位置: 首頁>>代碼示例>>Python>>正文


Python server.HTTPServer方法代碼示例

本文整理匯總了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() 
開發者ID:PiDelport,項目名稱:django-payfast,代碼行數:20,代碼來源:itn_helpers.py

示例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() 
開發者ID:Orange-OpenSource,項目名稱:pyDcop,代碼行數:19,代碼來源:communication.py

示例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() 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:21,代碼來源:docs.py

示例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() 
開發者ID:avocado-framework,項目名稱:avocado-vt,代碼行數:20,代碼來源:http_server.py

示例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) 
開發者ID:korfuri,項目名稱:django-prometheus,代碼行數:27,代碼來源:exports.py

示例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!") 
開發者ID:kasappeal,項目名稱:sparrest,代碼行數:20,代碼來源:server.py

示例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() 
開發者ID:gramps-project,項目名稱:addons-source,代碼行數:28,代碼來源:topola_server.py

示例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 
開發者ID:C0D3D3V,項目名稱:Moodle-Downloader-2,代碼行數:26,代碼來源:sso_token_receiver.py

示例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() 
開發者ID:facebookresearch,項目名稱:ParlAI,代碼行數:24,代碼來源:interactive_web.py

示例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) 
開發者ID:stefanhoelzl,項目名稱:vue.py,代碼行數:24,代碼來源:conftest.py

示例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() 
開發者ID:wdxtub,項目名稱:deep-learning-note,代碼行數:11,代碼來源:1_myhttpd.py

示例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() 
開發者ID:hankcs,項目名稱:pyhanlp,代碼行數:7,代碼來源:server.py

示例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 
開發者ID:jojoin,項目名稱:cutout,代碼行數:8,代碼來源:http.py

示例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 
開發者ID:wolfmanjm,項目名稱:kivy-smoothie-host,代碼行數:17,代碼來源:web_server.py

示例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() 
開發者ID:jrmdev,項目名稱:mitm_relay,代碼行數:13,代碼來源:mitm_relay.py


注:本文中的http.server.HTTPServer方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。