[python] Explicitly bind HTTP server to localhost (#8880)

On Windows, Python 3 is unable to listen on `0.0.0.0` and errors with:

```
[WinError 10049] The requested address is not valid in its context
```

The only solution I found is to bind to `127.0.0.1` or `localhost`. I've run into issues before with using `localhost`, so I chose to go with `127.0.0.1` and Windows (and macOS) seems to be happy.

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This commit is contained in:
Chris Barber
2022-11-10 20:33:31 -06:00
committed by GitHub
parent 5669fad6bc
commit 71e233ce7f

View File

@@ -4,6 +4,7 @@ import json
import inspect
from importlib import util
from http.server import BaseHTTPRequestHandler
import socket
# Import relative path https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
__vc_spec = util.spec_from_file_location("__VC_HANDLER_MODULE_NAME", "./__VC_HANDLER_ENTRYPOINT")
@@ -37,7 +38,7 @@ if 'handler' in __vc_variables or 'Handler' in __vc_variables:
import http
import _thread
server = HTTPServer(('', 0), base)
server = HTTPServer(('127.0.0.1', 0), base)
port = server.server_address[1]
def vc_handler(event, context):
@@ -57,8 +58,11 @@ if 'handler' in __vc_variables or 'Handler' in __vc_variables:
body = base64.b64decode(body)
request_body = body.encode('utf-8') if isinstance(body, str) else body
conn = http.client.HTTPConnection('0.0.0.0', port)
conn.request(method, path, headers=headers, body=request_body)
conn = http.client.HTTPConnection('127.0.0.1', port)
try:
conn.request(method, path, headers=headers, body=request_body)
except (http.client.HTTPException, socket.error) as ex:
print ("Request Error: %s" % ex)
res = conn.getresponse()
return_dict = {