Skip to content

Commit cd8d2ce

Browse files
committed
refactor: improve requests handling
1 parent a301064 commit cd8d2ce

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

core/requests.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,37 +80,41 @@ def encode_file(name: str, filename: str, data: bytes, boundary: str, CRLF: str,
8080

8181

8282

83-
def http_request(url: str, method: str, auth_token: str = None, metadata: dict = None, blob: bytes = None, longpoll: int = None) -> dict:
83+
def http_request(url: str, method: str, auth_token: str = None, metadata: dict = None, blob: bytes = None, longpoll: int = None) -> bytes:
8484
if method.upper() not in ["POST", "GET", "PUT", "DELETE"]:
8585
raise ValueError(f"Invalid request method `{method}`")
8686

8787

8888
if method.upper() in ["POST", "PUT"]:
89-
if metadata and blob:
89+
if blob:
9090

9191
# a-zA-Z0-9, same as what Chromium-based browser do.
9292
ALPHABET_ASCII = string.ascii_letters + string.digits
9393
ALPHABET_LENGTH = len(ALPHABET_ASCII)
9494

9595
boundary = "WebKitFormBoundary"
96-
boundary += ''.join(ALPHABET_ASCII[b % ALPHABET_LENGTH] for b in sha3_512(secrets.token_bytes(16)[:16]))
96+
boundary += ''.join(ALPHABET_ASCII[b % ALPHABET_LENGTH] for b in sha3_512(secrets.token_bytes(16))[:16])
9797

9898
CRLF = "\r\n"
9999
body = b""
100100

101101
if metadata is not None:
102102
body += encode_field("metadata", json.dumps(metadata), boundary, CRLF)
103103

104-
if blob is not None:
105-
body += encode_file("blob", "blob.bin", blob, boundary, CRLF)
104+
body += encode_file("blob", "blob.bin", blob, boundary, CRLF)
105+
106+
if not body.endswith(CRLF.encode("utf-8")):
107+
body += CRLF.encode("utf-8")
108+
106109

107110
body += f'--{boundary}--{CRLF}'.encode("utf-8")
108111

109112

110113
req = request.Request(
111114
url,
112115
data = body,
113-
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}
116+
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
117+
method = method.upper()
114118
)
115119

116120
elif metadata:

0 commit comments

Comments
 (0)