当前位置:首页 > 项目 > Wpython > 正文内容

micropython 实现文件下载保存到本地

Watrt3年前 (2023-05-31)Wpython16130
import sys
import gc
import ussl
import usocket

gc.collect()
debug = False
index_urls = ["https://micropython.org/pi", "https://pypi.org/pypi"]
install_path = None
cleanup_files = []

file_buf = bytearray(512)
warn_ussl = True

def url_open(url):
    global warn_ussl

    if debug:
        print(url)

    proto, _, host, urlpath = url.split("/", 3)
    try:
        if proto == "https:":
            port = 443
        else:
            port = 80
        if ":" in host:
            host, port = host.split(":")
            port = int(port)
        ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
    except OSError as e:
        fatal("Unable to resolve %s (no Internet?)" % host, e)
        print("Address infos:", ai)
    ai = ai[0]

    s = usocket.socket(ai[0], ai[1], ai[2])
    try:
        # print("Connect address:", addr)
        s.connect(ai[-1])

        if proto == "https:":
            s = ussl.wrap_socket(s, server_hostname=host)
            if warn_ussl:
                print("Warning: %s SSL certificate is not validated" % host)
                warn_ussl = False

        # MicroPython rawsocket module supports file interface directly
        s.write("GET /%s HTTP/1.0\r\nHost: %s:%s\r\n\r\n" % (urlpath, host, port))
        l = s.readline()
        protover, status, msg = l.split(None, 2)
        if status != b"200":
            if status == b"404" or status == b"301":
                raise NotFoundError("Package not found")
            raise ValueError(status)
        while 1:
            l = s.readline()
            if not l:
                raise ValueError("Unexpected EOF in HTTP headers")
            if l == b"\r\n":
                break
    except Exception as e:
        s.close()
        raise e
    return s
def download(url,fname=None,length=512):
  file_buf = bytearray(length)
  downloadfile=url_open(url)
  if not fname:
      fname=url.split('/')[-1]
  with open(fname, "wb") as outf:
      while True:
          sz = downloadfile.readinto(file_buf)
          if not sz:
              break
          outf.write(file_buf, sz)
  
def fatal(msg, exc=None):
    print("Error:", msg)
    if exc and debug:
        raise exc
    sys.exit(1)

#cc=url_open("http://app.xb6.cn/home/api")
download("https://www.west.cn/images2016/logo.jpg",'/img/l.jpg')

download("https://www.west.cn/images2016/logo.jpg",'/img/l.jpg')  第一个参数为下载地址 第二个参数为本地保存位置

打赏 支付宝打赏 微信打赏
分享给朋友:

相关文章

LVGL_micropython 模拟器

LVGL_micropython 模拟器

在使用micropython编写lvgl界面时有时间非常的麻烦。要在设备上才看得到效果。比较麻烦。npx的GUI-Guider软件中的模拟器给抠出来了单独使用,非常不错。下面是运行实例:import SDL import utime as time import usys as sys import lvgl as lv import lodepng as p...

micropython 连接到mqtt

micropython 连接到mqtt

from umqtt.simple import MQTTClient from machine import Pin import ujson import urequests import network import time SERVER = "www.028sd.net" CLIENT_ID = "e...

micropython文本编辑器 界面

micropython文本编辑器 界面

##### startup script ##### #!/opt/bin/lv_micropython -i import lvgl as lv import display_driver ##### main script ##### import fs_driver fs_drv = lv.fs_drv_t() f...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。