Skip to content

Commit

Permalink
fixed accessing/setting Response headers
Browse files Browse the repository at this point in the history
  • Loading branch information
zNitche committed May 19, 2024
1 parent 14ef374 commit a887258
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 11 deletions.
2 changes: 1 addition & 1 deletion lightberry/core/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ async def requests_handler(self, request):

response = await asyncio.wait_for(self.__process_request(request), self.config.TIMEOUT)

self.__print_debug(f"response header: '{response.get_headers()}'")
self.__print_debug(f"response header: '{response.get_headers_string()}'")

except Exception as e:
self.__print_debug(f"error while handing request", exception=e)
Expand Down
18 changes: 11 additions & 7 deletions lightberry/core/communication/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class Response:
def __init__(self, status_code: int = 200, content_type: str = HTTPConsts.CONTENT_TYPE_JSON, payload: str = None):
self.headers: dict[str, ...] = {}
self.__headers: dict[str, ...] = {}
self.status_code: int = status_code
self.content_type: str = content_type

Expand All @@ -14,31 +14,35 @@ def __init__(self, status_code: int = 200, content_type: str = HTTPConsts.CONTEN
def get_content_length(self) -> int:
return len(self.payload) if self.payload else 0

def get_headers(self) -> str:
def get_headers_string(self) -> str:
header_rows = [f"HTTP/1.1 {self.status_code}",
f"CONTENT-LENGTH: {self.get_content_length()}"]

for header, value in self.headers.items():
for header, value in self.__headers.items():
header_rows.append(f"{header}: {value}")

if HTTPConsts.CONTENT_TYPE not in header_rows:
if HTTPConsts.CONTENT_TYPE not in self.__headers.keys():
header_rows.append(f"{HTTPConsts.CONTENT_TYPE}: {self.content_type}")

header_string = "\r\n".join(header_rows)

return header_string

@property
def headers(self):
return self.__headers.copy()

def add_header(self, name: str, value):
normalized_name = name.upper()

if normalized_name not in self.headers.keys():
self.headers[normalized_name] = value
if normalized_name not in self.__headers.keys():
self.__headers[normalized_name] = value

def get_body(self) -> str:
return self.payload if self.payload else ""

def get_response_string(self) -> str:
headers = self.get_headers()
headers = self.get_headers_string()
body = self.get_body()

return f"{headers}\r\n\r\n{body}"
2 changes: 1 addition & 1 deletion lightberry/core/sockets_servers/http/app_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async def __requests_handler(self, client_r: StreamReader, client_w: StreamWrite
response = await asyncio.wait_for(self.__app.requests_handler(request), self.__app.config.TIMEOUT)

if response.is_payload_streamed:
requests_utils.write_to_stream(client_w, f"{response.get_headers()}\r\n\r\n")
requests_utils.write_to_stream(client_w, f"{response.get_headers_string()}\r\n\r\n")
await client_w.drain()

for chunk in response.get_body():
Expand Down
4 changes: 2 additions & 2 deletions lightberry/shortcuts.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ def redirect(url: str) -> Response:

if url:
response = Response(301)
response.headers["LOCATION"] = url
response.add_header("LOCATION", url)

return response


def send_file(file_path: str, filename: str) -> FileResponse:
response = FileResponse(file_path=file_path)
response.headers["Content-Disposition"] = f"attachment; filename={filename}"
response.add_header("Content-Disposition", f"attachment; filename={filename}")

return response

Expand Down

0 comments on commit a887258

Please sign in to comment.