1+ # SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries
2+ #
3+ # SPDX-License-Identifier: MIT
4+ """
5+ `adafruit_httpserver.response.HTTPResponse`
6+ ====================================================
7+ * Author(s): Dan Halbert, Michał Pokusa
8+ """
9+
110try :
211 from typing import Optional , Dict , Union
312 from socket import socket
13+ from socketpool import SocketPool
414except ImportError :
515 pass
616
717from errno import EAGAIN , ECONNRESET
818import os
919
10- from socketpool import SocketPool
1120
1221from .mime_type import MIMEType
1322from .status import HTTPStatus , CommonHTTPStatus
1423
24+
1525class HTTPResponse :
1626 """Details of an HTTP response. Use in `HTTPServer.route` decorator functions."""
1727
@@ -33,7 +43,7 @@ def __init__(
3343 content_type : str = MIMEType .TXT ,
3444 filename : Optional [str ] = None ,
3545 root_path : str = "" ,
36- http_version : str = "HTTP/1.1"
46+ http_version : str = "HTTP/1.1" ,
3747 ) -> None :
3848 """
3949 Creates an HTTP response.
@@ -65,7 +75,7 @@ def _construct_response_bytes(
6575 headers = headers or {}
6676
6777 headers .setdefault ("Content-Type" , content_type )
68- headers .setdefault ("Content-Length" , content_length if content_length is not None else len (body ))
78+ headers .setdefault ("Content-Length" , content_length or len (body ))
6979 headers .setdefault ("Connection" , "close" )
7080
7181 for header , value in headers .items ():
@@ -75,7 +85,7 @@ def _construct_response_bytes(
7585
7686 return response
7787
78- def send (self , conn : Union [SocketPool .Socket , socket .socket ]) -> None :
88+ def send (self , conn : Union [" SocketPool.Socket" , " socket.socket" ]) -> None :
7989 """
8090 Send the constructed response over the given socket.
8191 """
@@ -85,60 +95,60 @@ def send(self, conn: Union[SocketPool.Socket, socket.socket]) -> None:
8595 file_length = os .stat (self .root_path + self .filename )[6 ]
8696 self ._send_file_response (
8797 conn ,
88- filename = self .filename ,
89- root_path = self .root_path ,
90- file_length = file_length ,
91- headers = self .headers ,
98+ filename = self .filename ,
99+ root_path = self .root_path ,
100+ file_length = file_length ,
101+ headers = self .headers ,
92102 )
93103 except OSError :
94104 self ._send_response (
95105 conn ,
96- status = CommonHTTPStatus .NOT_FOUND_404 ,
97- content_type = MIMEType .TXT ,
98- body = f"{ CommonHTTPStatus .NOT_FOUND_404 } { self .filename } " ,
106+ status = CommonHTTPStatus .NOT_FOUND_404 ,
107+ content_type = MIMEType .TXT ,
108+ body = f"{ CommonHTTPStatus .NOT_FOUND_404 } { self .filename } " ,
99109 )
100110 else :
101111 self ._send_response (
102112 conn ,
103- status = self .status ,
104- content_type = self .content_type ,
105- headers = self .headers ,
106- body = self .body ,
113+ status = self .status ,
114+ content_type = self .content_type ,
115+ headers = self .headers ,
116+ body = self .body ,
107117 )
108118
109119 def _send_response (
110120 self ,
111- conn : Union [SocketPool .Socket , socket .socket ],
121+ conn : Union [" SocketPool.Socket" , " socket.socket" ],
112122 status : HTTPStatus ,
113123 content_type : str ,
114124 body : str ,
115- headers : Dict [str , str ] = None
125+ headers : Dict [str , str ] = None ,
116126 ):
117127 self ._send_bytes (
118128 conn ,
119129 self ._construct_response_bytes (
120- status = status ,
121- content_type = content_type ,
122- headers = headers ,
123- body = body ,
124- )
130+ status = status ,
131+ content_type = content_type ,
132+ headers = headers ,
133+ body = body ,
134+ ),
125135 )
126136
127137 def _send_file_response (
128138 self ,
129- conn : Union [SocketPool .Socket , socket .socket ],
139+ conn : Union [" SocketPool.Socket" , " socket.socket" ],
130140 filename : str ,
131141 root_path : str ,
132142 file_length : int ,
133- headers : Dict [str , str ] = None
143+ headers : Dict [str , str ] = None ,
134144 ):
135145 self ._send_bytes (
136146 conn ,
137147 self ._construct_response_bytes (
138- status = self .status ,
139- content_type = MIMEType .from_file_name (filename ),
140- content_length = file_length ,
141- headers = headers ,
148+ status = self .status ,
149+ content_type = MIMEType .from_file_name (filename ),
150+ content_length = file_length ,
151+ headers = headers ,
142152 ),
143153 )
144154 with open (root_path + filename , "rb" ) as file :
@@ -147,7 +157,7 @@ def _send_file_response(
147157
148158 @staticmethod
149159 def _send_bytes (
150- conn : Union [SocketPool .Socket , socket .socket ],
160+ conn : Union [" SocketPool.Socket" , " socket.socket" ],
151161 buffer : Union [bytes , bytearray , memoryview ],
152162 ):
153163 bytes_sent = 0
@@ -157,5 +167,7 @@ def _send_bytes(
157167 try :
158168 bytes_sent += conn .send (view [bytes_sent :])
159169 except OSError as exc :
160- if exc .errno == EAGAIN : continue
161- if exc .errno == ECONNRESET : return
170+ if exc .errno == EAGAIN :
171+ continue
172+ if exc .errno == ECONNRESET :
173+ return
0 commit comments