@@ -38,12 +38,15 @@ def request(
38
38
url ,
39
39
data = None ,
40
40
json = None ,
41
- headers = {} ,
41
+ headers = None ,
42
42
stream = None ,
43
43
auth = None ,
44
44
timeout = None ,
45
45
parse_headers = True ,
46
46
):
47
+ if headers is None :
48
+ headers = {}
49
+
47
50
redirect = None # redirection url, None means no redirection
48
51
chunked_data = data and getattr (data , "__next__" , None ) and not getattr (data , "__len__" , None )
49
52
@@ -94,33 +97,49 @@ def request(
94
97
context .verify_mode = tls .CERT_NONE
95
98
s = context .wrap_socket (s , server_hostname = host )
96
99
s .write (b"%s /%s HTTP/1.0\r \n " % (method , path ))
100
+
97
101
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
+
105
104
if json is not None :
106
105
assert data is None
107
106
import ujson
108
107
109
108
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
+
111
113
if data :
112
114
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
+
117
132
if data :
118
133
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 )
124
143
else :
125
144
s .write (data )
126
145
0 commit comments