Guest User

Wget

a guest
Jul 23rd, 2024
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.11 KB | None | 0 0
  1. import gc
  2. import usocket
  3.  
  4. class Response:
  5.  
  6.     def __init__(self, f):
  7.         self.raw = f
  8.         self.encoding = "utf-8"
  9.         self._cached = None
  10.  
  11.     def close(self):
  12.         if self.raw:
  13.             self.raw.close()
  14.             self.raw = None
  15.         self._cached = None
  16.  
  17.     @property
  18.     def content(self):
  19.         if self._cached is None:
  20.             try:
  21.                 self._cached = self.raw.read()
  22.             finally:
  23.                 self.raw.close()
  24.                 self.raw = None
  25.         return self._cached
  26.  
  27.     @property
  28.     def text(self):
  29.         return str(self.content, self.encoding)
  30.  
  31.     def json(self):
  32.         import ujson
  33.         return ujson.loads(self.content)
  34.  
  35.  
  36. def request(method, url, data=None, json=None, headers={}, stream=None, parse_headers=True):
  37.     redir_cnt = 1
  38.     if json is not None:
  39.         assert data is None
  40.         import ujson
  41.         data = ujson.dumps(json)
  42.  
  43.     while True:
  44.         try:
  45.             proto, dummy, host, path = url.split("/", 3)
  46.         except ValueError:
  47.             proto, dummy, host = url.split("/", 2)
  48.             path = ""
  49.         if proto == "http:":
  50.             port = 80
  51.         elif proto == "https:":
  52.             import ussl
  53.             port = 443
  54.         else:
  55.             raise ValueError("Unsupported protocol: " + proto)
  56.  
  57.         if ":" in host:
  58.             host, port = host.split(":", 1)
  59.             port = int(port)
  60.  
  61.         ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
  62.         ai = ai[0]
  63.  
  64.         resp_d = None
  65.         if parse_headers is not False:
  66.             resp_d = {}
  67.  
  68.         s = usocket.socket(ai[0], ai[1], ai[2])
  69.         try:
  70.             s.connect(ai[-1])
  71.             if proto == "https:":
  72.                 s = ussl.wrap_socket(s, server_hostname=host)
  73.             s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
  74.             if not "Host" in headers:
  75.                 s.write(b"Host: %s\r\n" % host)
  76.             # Iterate over keys to avoid tuple alloc
  77.             for k in headers:
  78.                 s.write(k)
  79.                 s.write(b": ")
  80.                 s.write(headers[k])
  81.                 s.write(b"\r\n")
  82.             if json is not None:
  83.                 s.write(b"Content-Type: application/json\r\n")
  84.             if data:
  85.                 s.write(b"Content-Length: %d\r\n" % len(data))
  86.             s.write(b"Connection: close\r\n\r\n")
  87.             if data:
  88.                 s.write(data)
  89.  
  90.             l = s.readline()
  91.             #print(l)
  92.             l = l.split(None, 2)
  93.             status = int(l[1])
  94.             reason = ""
  95.             if len(l) > 2:
  96.                 reason = l[2].rstrip()
  97.             while True:
  98.                 l = s.readline()
  99.                 if not l or l == b"\r\n":
  100.                     break
  101.                 #print(l)
  102.  
  103.                 if l.startswith(b"Transfer-Encoding:"):
  104.                     if b"chunked" in l:
  105.                         raise ValueError("Unsupported " + l.decode())
  106.                 elif l.startswith(b"Location:") and 300 <= status <= 399:
  107.                     if not redir_cnt:
  108.                         raise ValueError("Too many redirects")
  109.                     redir_cnt -= 1
  110.                     url = l[9:].decode().strip()
  111.                     #print("redir to:", url)
  112.                     status = 300
  113.                     break
  114.  
  115.                 if parse_headers is False:
  116.                     pass
  117.                 elif parse_headers is True:
  118.                     l = l.decode()
  119.                     k, v = l.split(":", 1)
  120.                     resp_d[k] = v.strip()
  121.                 else:
  122.                     parse_headers(l, resp_d)
  123.         except OSError:
  124.             s.close()
  125.             raise
  126.  
  127.         if status != 300:
  128.             break
  129.  
  130.     resp = Response(s)
  131.     resp.status_code = status
  132.     resp.reason = reason
  133.     if resp_d is not None:
  134.         resp.headers = resp_d
  135.     return resp
  136.  
  137.  
  138. def head(url, **kw):
  139.     return request("HEAD", url, **kw)
  140.  
  141. def get(url, **kw):
  142.     return request("GET", url, **kw)
  143.  
  144. def post(url, **kw):
  145.     return request("POST", url, **kw)
  146.  
  147. def put(url, **kw):
  148.     return request("PUT", url, **kw)
  149.  
  150. def patch(url, **kw):
  151.     return request("PATCH", url, **kw)
  152.  
  153. def delete(url, **kw):
  154.     return request("DELETE", url, **kw)
  155.  
  156.  
  157. def wget(url="",path=""):
  158.     from os import mkdir
  159.     from gc import collect
  160.     debug = False
  161.     filename = url.split("/")[-1]
  162.    
  163.     valid_chars = '-_.()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  164.     correc_filename = ''.join(c for c in filename if c in valid_chars)
  165.    
  166.     if filename != correc_filename:
  167.         print("Chybne zadan nazev souboru, automaticky opraven na:" + correc_filename)
  168.    
  169.     if path != "":
  170.         try:
  171.             if path.endswith('/'):
  172.                 path = path[:-1]
  173.             os.mkdir(path)
  174.             path = path + "/"
  175.         except:
  176.             pass
  177.    
  178.     gc.collect()
  179.     try:
  180.         if debug: print("get")
  181.         res = get(url, stream = True)
  182.         if debug: print("get done")
  183.         if debug: print(res.status_code)
  184.         gc.collect()
  185.         if res.status_code == 200:
  186.             if debug: print("opening file")
  187.             f = open(path+correc_filename, 'w')
  188.             if debug: print("opened file")
  189.             while True:
  190.                 if debug: print("reading chunk")
  191.                 chunk = res.raw.read(256)
  192.                 if debug: print("writing chunk")
  193.                 #if debug: print(chunk)
  194.                 f.write(chunk)
  195.                 if debug: print("chunk writen")
  196.                 if not chunk:
  197.                     break
  198.             f.close()
  199.             print("Hotovo")
  200.         elif res.status_code == 404:
  201.             print("Soubor nenalezen")
  202.         else:
  203.             print("Chyba:",res.status_code)
  204.     except Exception as e:
  205.         print("Error, exception: {0}".format(e))
  206.  
  207. print("Stahuji ide_1_20.tar")
  208. wget(url="http://iotserver.cz/ide/ide_1_20.tar",path="")
  209.  
  210. print("Stahuji install_1_20.py")
  211. wget(url="http://iotserver.cz/ide/install_1_20.py",path="")
  212.  
  213. print("Spoustim instalator...")
  214. import install_1_20.py
Tags: wget
Advertisement
Add Comment
Please, Sign In to add comment