Skip to content

Instantly share code, notes, and snippets.

@thehappycheese
Created October 10, 2023 05:51
Show Gist options
  • Save thehappycheese/cb09ef8d28d6c296d71619739b1212dc to your computer and use it in GitHub Desktop.
Save thehappycheese/cb09ef8d28d6c296d71619739b1212dc to your computer and use it in GitHub Desktop.
Starts a thread and serves the given data just once before closing the thread. Use with Selenium.
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
def serve_once(data:str, port=8000, host="127.0.0.1"):
"""
Serves the given data on the given port and host, then returns after
responding to one request.
This is a helpful way to send HTML to a browser being controled using Selenium.
"""
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(data.encode("utf-8"))
httpd = None
def run_localhost_server_in_thread():
nonlocal httpd
httpd = HTTPServer((host, port), MyServer)
print("Serving once...")
httpd.handle_request()
print("Served once.")
thread = threading.Thread(target=run_localhost_server_in_thread)
thread.start()
return thread
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment