micropython的urequests库

我使用的esp32cam固件没有urequests库,所以自己找了一个,放在esp32cam里就可以使用了

import usocket
class Response:
    def __init__(self,f):
        self.raw=f
        self.encoding="utf-8"
        self._cached=None
    def close(self):
        if self.raw:
            self.raw.close()
            self.raw=None
        self._cached=None
    @property
    def content(self):
        if self._cached is None:
            try:
                self._cached=self.raw.read()
            finally:
                self.raw.close()
                self.raw=None
        return self._cached
    @property
    def text(self):
        return str(self.content,self.encoding)
    def json(self):
        import ujson
        return ujson.loads(self.content)
def request(method,url,data=None,json=None,headers={},stream=None,auth=None,timeout=None,parse_headers=True):
    redirect=None
    chunked_data=data and getattr(data,"__iter__", None) and not getattr(data,"__len__",None)
    if auth is not None:
        import ubinascii
        username,password=auth
        formated=b"{}:{}".format(username,password)
        formated=str(ubinascii.b2a_base64(formated)[:-1],"ascii")
        headers["Authorization"]="Basic {}".format(formated)
    try:
        proto,dummy,host,path=url.split("/",3)
    except ValueError:
        proto,dummy,host=url.split("/",2)
        path=""
    if proto=="http:":
        port=80
    elif proto=="https:":
        import ussl
        port=443
    else:
        raise ValueError("Unsupported protocol: "+proto)
    if ":" in host:
        host,port=host.split(":",1)
        port=int(port)
    ai=usocket.getaddrinfo(host,port,0,usocket.SOCK_STREAM)
    ai=ai[0]
    resp_d=None
    if parse_headers is not False:
        resp_d={}
    s=usocket.socket(ai[0],usocket.SOCK_STREAM,ai[2])
    if timeout is not None:
        s.settimeout(timeout)
    try:
        s.connect(ai[-1])
        if proto=="https:":
            s=ussl.wrap_socket(s, server_hostname=host)
        s.write(b"%s /%s HTTP/1.0\r\n"%(method, path))
        if not "Host" in headers:
            s.write(b"Host: %s\r\n"%host)
        for k in headers:
            s.write(k)
            s.write(b":")
            s.write(headers[k])
            s.write(b"\r\n")
        if json is not None:
            assert data is None
            import ujson
 
            data=ujson.dumps(json)
            s.write(b"Content-Type: application/json\r\n")
        if data:
            if chunked_data:
                s.write(b"Transfer-Encoding: chunked\r\n")
            else:
                s.write(b"Content-Length: %d\r\n"%len(data))
        s.write(b"Connection: close\r\n\r\n")
        if data:
            if chunked_data:
                for chunk in data:
                    s.write(b"%x\r\n"%len(chunk))
                    s.write(chunk)
                    s.write(b"\r\n")
                s.write("0\r\n\r\n")
            else:
                s.write(data)
        l=s.readline()
        l=l.split(None, 2)
        if len(l)<2:
            raise ValueError("HTTP error: BadStatusLine:\n%s"%l)
        status=int(l[1])
        reason=""
        if len(l)>2:
            reason=l[2].rstrip()
        while True:
            l=s.readline()
            if not l or l==b"\r\n":
                break
            if l.startswith(b"Transfer-Encoding:"):
                if b"chunked" in l:
                    raise ValueError("Unsupported"+str(l,"utf-8"))
            elif l.startswith(b"Location:") and not 200<=status<=299:
                if status in [301,302,303,307,308]:
                    redirect=str(l[10:-2],"utf-8")
                else:
                    raise NotImplementedError("Redirect %d not yet supported"%status)
            if parse_headers is False:
                pass
            elif parse_headers is True:
                l=str(l,"utf-8")
                k,v=l.split(":",1)
                resp_d[k]=v.strip()
            else:
                parse_headers(l,resp_d)
    except OSError:
        s.close()
        raise
    if redirect:
        s.close()
        if status in [301,302,303]:
            return request("GET",redirect,None,None,headers,stream)
        else:
            return request(method,redirect,data,json,headers,stream)
    else:
        resp=Response(s)
        resp.status_code=status
        resp.reason=reason
        if resp_d is not None:
            resp.headers=resp_d
        return resp
def head(url,**kw):
    return request("HEAD",url,**kw)
def get(url,**kw):
    return request("GET",url,**kw)
def post(url,**kw):
    return request("POST",url,**kw)
def put(url,**kw):
    return request("PUT",url,**kw)
def patch(url,**kw):
    return request("PATCH",url,**kw)
def delete(url,**kw):
    return request("DELETE",url,**kw)

2022 / 01/ 30: 新版esptool 刷micropython固件指令不是 esptool.py cmd... 而是 esptool cmd... 即可;另外rshell 在 >= python 3.10 的时候出错解决方法可以查看:  已于2022年发布的: 第二章:修复rshell在python3.10出错 免费内容: https://edu.csdn.net/course/detail/29666 2025/07/07: 由于该视频在2019年制作,当时py3.7;现在py3.13 由于pyreadline冲突rshell已不能用;如果仍要使用rshell请安装py3.12并用我修改的rshell: https://github.com/gamefunc/rshell/releases micropython语法和python3一样,编写起来非常方便。如果你快速入门单片机玩物联网而且像轻松实现各种功能,那绝力推荐使用micropython。方便易懂易学。 同时如果你懂C语音,也可以用C写好函数并编译进micropython固件里然后进入micropython调用(非必须)。 能通过WIFI联网(2.1章),也能通过sim卡使用2G/3G/4G/5G联网(4.5章)。 为实现语音控制,本教程会教大家使用tensorflow利用神经网络训练自己的语音模型并应用。为实现通过网页控制,本教程会教大家linux(debian10 nginx->uwsgi->python3->postgresql)网站前后台入门。为记录单片机传输过来的数据, 本教程会教大家入门数据。  本教程会通过通俗易懂的比喻来讲解各种原理与思路,并手把手编写程序来实现各项功能。 本教程micropython版本是 2019年6月发布的1.11; 更多内容请看视频列表。  学习这门课程之前你需要至少掌握: 1: python3基础(变量, 循环, 函数, 常用, 常用方法)。 本视频使用到的零件与淘宝上大致价格:     1: 超声波传感器(3)     2: MAX9814麦克风放大模块(8)     3: DHT22(15)     4: LED(0.1)     5: 8路5V低电平触发继电器(12)     6: HX1838红外接收模块(2)     7:红外发射管(0.1),HX1838红外接收板(1)     other: 电表, 排线, 面包板(2)*2,ESP32(28)  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值