Start an HTTP server thread on a specific port. Start an HTML/text server thread, so HTML or text documents can be browsed dynamically and interactively with a web browser. Example use: >>> import time >>> import pydoc Define a URL handler. To determine w
(urlhandler, hostname, port)
| 2379 | # --------------------------------------- enhanced web browser interface |
| 2380 | |
| 2381 | def _start_server(urlhandler, hostname, port): |
| 2382 | """Start an HTTP server thread on a specific port. |
| 2383 | |
| 2384 | Start an HTML/text server thread, so HTML or text documents can be |
| 2385 | browsed dynamically and interactively with a web browser. Example use: |
| 2386 | |
| 2387 | >>> import time |
| 2388 | >>> import pydoc |
| 2389 | |
| 2390 | Define a URL handler. To determine what the client is asking |
| 2391 | for, check the URL and content_type. |
| 2392 | |
| 2393 | Then get or generate some text or HTML code and return it. |
| 2394 | |
| 2395 | >>> def my_url_handler(url, content_type): |
| 2396 | ... text = 'the URL sent was: (%s, %s)' % (url, content_type) |
| 2397 | ... return text |
| 2398 | |
| 2399 | Start server thread on port 0. |
| 2400 | If you use port 0, the server will pick a random port number. |
| 2401 | You can then use serverthread.port to get the port number. |
| 2402 | |
| 2403 | >>> port = 0 |
| 2404 | >>> serverthread = pydoc._start_server(my_url_handler, port) |
| 2405 | |
| 2406 | Check that the server is really started. If it is, open browser |
| 2407 | and get first page. Use serverthread.url as the starting page. |
| 2408 | |
| 2409 | >>> if serverthread.serving: |
| 2410 | ... import webbrowser |
| 2411 | |
| 2412 | The next two lines are commented out so a browser doesn't open if |
| 2413 | doctest is run on this module. |
| 2414 | |
| 2415 | #... webbrowser.open(serverthread.url) |
| 2416 | #True |
| 2417 | |
| 2418 | Let the server do its thing. We just need to monitor its status. |
| 2419 | Use time.sleep so the loop doesn't hog the CPU. |
| 2420 | |
| 2421 | >>> starttime = time.monotonic() |
| 2422 | >>> timeout = 1 #seconds |
| 2423 | |
| 2424 | This is a short timeout for testing purposes. |
| 2425 | |
| 2426 | >>> while serverthread.serving: |
| 2427 | ... time.sleep(.01) |
| 2428 | ... if serverthread.serving and time.monotonic() - starttime > timeout: |
| 2429 | ... serverthread.stop() |
| 2430 | ... break |
| 2431 | |
| 2432 | Print any errors that may have occurred. |
| 2433 | |
| 2434 | >>> print(serverthread.error) |
| 2435 | None |
| 2436 | """ |
| 2437 | import http.server |
| 2438 | import email.message |
no test coverage detected