Skip to content

Commit

Permalink
delay the body read in HttpResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
keijack committed Jun 7, 2022
1 parent 32e4497 commit ec9bec6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 17 deletions.
2 changes: 1 addition & 1 deletion py_eureka_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
SOFTWARE.
"""

version = "0.11.2"
version = "0.11.3"

"""
Status of instances
Expand Down
44 changes: 28 additions & 16 deletions py_eureka_client/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,32 @@ def _to_urllib_request(self):

class HttpResponse:

def __init__(self) -> None:
self.raw_response = None
self.body_text = ''
def __init__(self, raw_response=None) -> None:
self.raw_response = raw_response
self.__body_read = False
self.__body_text = ''

def _read_body(self):
res = self.raw_response
if res.info().get("Content-Encoding") == "gzip":
f = gzip.GzipFile(fileobj=res)
else:
f = res
body_text = f.read().decode(_DEFAULT_ENCODING)
f.close()
return body_text

@property
def body_text(self):
if not self.__body_read:
self.__body_text = self._read_body()
self.__body_read = True
return self.__body_text

@body_text.setter
def body_text(self, val):
self.__body_text = val
self.__body_read = True


class HttpClient:
Expand All @@ -122,19 +145,8 @@ async def urlopen(self, request: Union[str, HttpRequest] = None,
else:
raise URLError("Unvalid URL")

res = HttpResponse()
res.raw_response = urllib.request.urlopen(req._to_urllib_request(), data=data, timeout=timeout)
res.body_text = self.__read_body(res.raw_response)
return res

def __read_body(self, res):
if res.info().get("Content-Encoding") == "gzip":
f = gzip.GzipFile(fileobj=res)
else:
f = res
body_text = f.read().decode(_DEFAULT_ENCODING)
f.close()
return body_text
res = urllib.request.urlopen(req._to_urllib_request(), data=data, timeout=timeout)
return HttpResponse(res)


http_client = HttpClient()
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ifaddr>=0.1.7
dnspython>=2.2.0

0 comments on commit ec9bec6

Please sign in to comment.