Skip to content

Commit 80b21be

Browse files
committed
requests: Make possible to override headers and allow raw data upload.
Signed-off-by: Mirza Kapetanovic <[email protected]>
1 parent ffb07db commit 80b21be

File tree

1 file changed

+37
-18
lines changed

1 file changed

+37
-18
lines changed

Diff for: python-ecosys/requests/requests/__init__.py

+37-18
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,15 @@ def request(
3838
url,
3939
data=None,
4040
json=None,
41-
headers={},
41+
headers=None,
4242
stream=None,
4343
auth=None,
4444
timeout=None,
4545
parse_headers=True,
4646
):
47+
if headers is None:
48+
headers = {}
49+
4750
redirect = None # redirection url, None means no redirection
4851
chunked_data = data and getattr(data, "__next__", None) and not getattr(data, "__len__", None)
4952

@@ -94,33 +97,49 @@ def request(
9497
context.verify_mode = tls.CERT_NONE
9598
s = context.wrap_socket(s, server_hostname=host)
9699
s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
100+
97101
if "Host" not in headers:
98-
s.write(b"Host: %s\r\n" % host)
99-
# Iterate over keys to avoid tuple alloc
100-
for k in headers:
101-
s.write(k)
102-
s.write(b": ")
103-
s.write(headers[k])
104-
s.write(b"\r\n")
102+
headers["Host"] = host
103+
105104
if json is not None:
106105
assert data is None
107106
import ujson
108107

109108
data = ujson.dumps(json)
110-
s.write(b"Content-Type: application/json\r\n")
109+
110+
if "Content-Type" not in headers:
111+
headers["Content-Type"] = "application/json"
112+
111113
if data:
112114
if chunked_data:
113-
s.write(b"Transfer-Encoding: chunked\r\n")
114-
else:
115-
s.write(b"Content-Length: %d\r\n" % len(data))
116-
s.write(b"Connection: close\r\n\r\n")
115+
if "Transfer-Encoding" not in headers and "Content-Length" not in headers:
116+
headers["Transfer-Encoding"] = "chunked"
117+
elif "Content-Length" not in headers:
118+
headers["Content-Length"] = str(len(data))
119+
120+
if "Connection" not in headers:
121+
headers["Connection"] = "close"
122+
123+
# Iterate over keys to avoid tuple alloc
124+
for k in headers:
125+
s.write(k)
126+
s.write(b": ")
127+
s.write(headers[k])
128+
s.write(b"\r\n")
129+
130+
s.write(b"\r\n")
131+
117132
if data:
118133
if chunked_data:
119-
for chunk in data:
120-
s.write(b"%x\r\n" % len(chunk))
121-
s.write(chunk)
122-
s.write(b"\r\n")
123-
s.write("0\r\n\r\n")
134+
if headers.get("Transfer-Encoding", None) == "chunked":
135+
for chunk in data:
136+
s.write(b"%x\r\n" % len(chunk))
137+
s.write(chunk)
138+
s.write(b"\r\n")
139+
s.write("0\r\n\r\n")
140+
else:
141+
for chunk in data:
142+
s.write(chunk)
124143
else:
125144
s.write(data)
126145

0 commit comments

Comments
 (0)