11import usocket , os
2- class Response :
32
3+
4+ class Response :
45 def __init__ (self , socket , saveToFile = None ):
56 self ._socket = socket
67 self ._saveToFile = saveToFile
7- self ._encoding = ' utf-8'
8+ self ._encoding = " utf-8"
89 if saveToFile is not None :
9- CHUNK_SIZE = 512 # bytes
10- with open (saveToFile , 'w' ) as outfile :
10+ CHUNK_SIZE = 512 # bytes
11+ with open (saveToFile , "w" ) as outfile :
1112 data = self ._socket .read (CHUNK_SIZE )
1213 while data :
1314 outfile .write (data )
1415 data = self ._socket .read (CHUNK_SIZE )
1516 outfile .close ()
16-
17+
1718 self .close ()
1819
1920 def close (self ):
@@ -24,7 +25,11 @@ def close(self):
2425 @property
2526 def content (self ):
2627 if self ._saveToFile is not None :
27- raise SystemError ('You cannot get the content from the response as you decided to save it in {}' .format (self ._saveToFile ))
28+ raise SystemError (
29+ "You cannot get the content from the response as you decided to save it in {}" .format (
30+ self ._saveToFile
31+ )
32+ )
2833
2934 try :
3035 result = self ._socket .read ()
@@ -39,96 +44,109 @@ def text(self):
3944 def json (self ):
4045 try :
4146 import ujson
47+
4248 result = ujson .load (self ._socket )
4349 return result
4450 finally :
4551 self .close ()
4652
4753
4854class HttpClient :
49-
5055 def __init__ (self , headers = {}):
5156 self ._headers = headers
5257
53- def request (self , method , url , data = None , json = None , file = None , custom = None , saveToFile = None , headers = {}, stream = None ):
58+ def request (
59+ self ,
60+ method ,
61+ url ,
62+ data = None ,
63+ json = None ,
64+ file = None ,
65+ custom = None ,
66+ saveToFile = None ,
67+ headers = {},
68+ stream = None ,
69+ ):
5470 def _write_headers (sock , _headers ):
5571 for k in _headers :
56- sock .write (b' {}: {}\r \n ' .format (k , _headers [k ]))
72+ sock .write (b" {}: {}\r \n " .format (k , _headers [k ]))
5773
5874 try :
59- proto , dummy , host , path = url .split ('/' , 3 )
75+ proto , dummy , host , path = url .split ("/" , 3 )
6076 except ValueError :
61- proto , dummy , host = url .split ('/' , 2 )
62- path = ''
63- if proto == ' http:' :
77+ proto , dummy , host = url .split ("/" , 2 )
78+ path = ""
79+ if proto == " http:" :
6480 port = 80
65- elif proto == ' https:' :
81+ elif proto == " https:" :
6682 import ussl
83+
6784 port = 443
6885 else :
69- raise ValueError (' Unsupported protocol: ' + proto )
86+ raise ValueError (" Unsupported protocol: " + proto )
7087
71- if ':' in host :
72- host , port = host .split (':' , 1 )
88+ if ":" in host :
89+ host , port = host .split (":" , 1 )
7390 port = int (port )
7491
7592 ai = usocket .getaddrinfo (host , port , 0 , usocket .SOCK_STREAM )
7693 if len (ai ) < 1 :
77- raise ValueError (' You are not connected to the internet...' )
94+ raise ValueError (" You are not connected to the internet..." )
7895 ai = ai [0 ]
7996
8097 s = usocket .socket (ai [0 ], ai [1 ], ai [2 ])
8198 try :
8299 s .connect (ai [- 1 ])
83- if proto == ' https:' :
100+ if proto == " https:" :
84101 s = ussl .wrap_socket (s , server_hostname = host )
85- s .write (b' %s /%s HTTP/1.0\r \n ' % (method , path ))
86- if not ' Host' in headers :
87- s .write (b' Host: %s\r \n ' % host )
102+ s .write (b" %s /%s HTTP/1.0\r \n " % (method , path ))
103+ if not " Host" in headers :
104+ s .write (b" Host: %s\r \n " % host )
88105 # Iterate over keys to avoid tuple alloc
89106 _write_headers (s , self ._headers )
90107 _write_headers (s , headers )
91108
92109 # add user agent
93- s .write (b' User-Agent: MicroPython Client\r \n ' )
110+ s .write (b" User-Agent: MicroPython Client\r \n " )
94111 if json is not None :
95112 assert data is None
96113 import ujson
114+
97115 data = ujson .dumps (json )
98- s .write (b' Content-Type: application/json\r \n ' )
116+ s .write (b" Content-Type: application/json\r \n " )
99117
100118 if data :
101- s .write (b' Content-Length: %d\r \n ' % len (data ))
102- s .write (b' \r \n ' )
119+ s .write (b" Content-Length: %d\r \n " % len (data ))
120+ s .write (b" \r \n " )
103121 s .write (data )
104122 elif file :
105- s .write (b' Content-Length: %d\r \n ' % os .stat (file )[6 ])
106- s .write (b' \r \n ' )
107- with open (file , 'r' ) as file_object :
123+ s .write (b" Content-Length: %d\r \n " % os .stat (file )[6 ])
124+ s .write (b" \r \n " )
125+ with open (file , "r" ) as file_object :
108126 for line in file_object :
109- s .write (line + ' \n ' )
127+ s .write (line + " \n " )
110128 elif custom :
111129 custom (s )
112130 else :
113- s .write (b' \r \n ' )
131+ s .write (b" \r \n " )
114132
115133 l = s .readline ()
116134 # print(l)
117135 l = l .split (None , 2 )
118136 status = int (l [1 ])
119- reason = ''
137+ reason = ""
120138 if len (l ) > 2 :
121139 reason = l [2 ].rstrip ()
122140 while True :
123141 l = s .readline ()
124- if not l or l == b' \r \n ' :
142+ if not l or l == b" \r \n " :
125143 break
126144 # print(l)
127- if l .startswith (b' Transfer-Encoding:' ):
128- if b' chunked' in l :
129- raise ValueError (' Unsupported ' + l )
130- elif l .startswith (b' Location:' ) and not 200 <= status <= 299 :
131- raise NotImplementedError (' Redirects not yet supported' )
145+ if l .startswith (b" Transfer-Encoding:" ):
146+ if b" chunked" in l :
147+ raise ValueError (" Unsupported " + l )
148+ elif l .startswith (b" Location:" ) and not 200 <= status <= 299 :
149+ raise NotImplementedError (" Redirects not yet supported" )
132150 except OSError :
133151 s .close ()
134152 raise
@@ -139,19 +157,19 @@ def _write_headers(sock, _headers):
139157 return resp
140158
141159 def head (self , url , ** kw ):
142- return self .request (' HEAD' , url , ** kw )
160+ return self .request (" HEAD" , url , ** kw )
143161
144162 def get (self , url , ** kw ):
145- return self .request (' GET' , url , ** kw )
163+ return self .request (" GET" , url , ** kw )
146164
147165 def post (self , url , ** kw ):
148- return self .request (' POST' , url , ** kw )
166+ return self .request (" POST" , url , ** kw )
149167
150168 def put (self , url , ** kw ):
151- return self .request (' PUT' , url , ** kw )
169+ return self .request (" PUT" , url , ** kw )
152170
153171 def patch (self , url , ** kw ):
154- return self .request (' PATCH' , url , ** kw )
172+ return self .request (" PATCH" , url , ** kw )
155173
156174 def delete (self , url , ** kw ):
157- return self .request (' DELETE' , url , ** kw )
175+ return self .request (" DELETE" , url , ** kw )
0 commit comments