If your goal is to not get an empty / invalid answer in your urlopen, the answer is you won't. You actually open a socket with this line:
http.server.HTTPServer(...)
so after it (with still one thread running) you already have an open socket listening for incoming connections (although nothing dispatching requests yet). After that we may have a race of two threads. Consider both possibilities:
- The server thread runs serve_forever first. Well, it's the case you're aiming at.
- The main thread connects first. Your connection will be accepted and will wait for something to dispatch it to the handler. Then the server thread runs serve_forever, attaches a dispatcher and your request still gets processed.