某个美丽的下午,运维把服务器上的nginx升级了,http协议也变成了http2.0,我本地的requests再也链接不到服务器,而后就找到了额hyperhtml
可是hyper的文档写的很简单,并且相比requests来讲还没那么人性化,看着demo说吧python
from hyper import HTTP20Connection conn = HTTP20Connection(host='xxx.xxx.xxx.xxx', port=80) # host直接写域名或者IP地址,不要加http或https # port默认是443 response = conn.request(method='POST', url='/post', body=None, headers=None) # 你会发现这里没有data参数 resp = conn.get_response(response) print(resp.read()) # 二进制,至关于requests中返回的res.content
你会发现,没有data参数,其实咱们也能想到就算写了data,最后咱们进行传输的时候data也会被放到body里面,可是具体怎么转化的,我参考了requests模块nginx
from collections.abc import Mapping from urllib.parse import urlencode def to_key_val_list(value): if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') if isinstance(value, Mapping): value = value.items() return list(value) def _encode_params(data): if isinstance(data, (str, bytes)): return data elif hasattr(data, 'read'): return data elif hasattr(data, '__iter__'): result = [] for k, vs in to_key_val_list(data): if isinstance(vs, (str, bytes)) or not hasattr(vs, '__iter__'): vs = [vs] for v in vs: if v is not None: result.append( (k.encode('utf-8') if isinstance(k, str) else k, v.encode('utf-8') if isinstance(v, str) else v)) return urlencode(result, doseq=True) else: return data data = {"name": "tom", "ege": "20"} print(_encode_params(data)) # name=tom&ege=20
上面这段代码是我从requests源码中截取出来的,能够直接运行,结果为name=tom&ege=20,看到这个咱们就明白如何转换的了,接下来咱们就能够用hyper发送表单数据了服务器
from hyper import HTTP20Connection conn = HTTP20Connection(host='xxx.xxx.xxx.xxx', port=80) response = conn.request(method='POST', url='/post', body='name=tom&age=20', headers={'Content-Type': 'application/x-www-form-urlencoded'}) resp = conn.get_response(response)
必定要记得加请求头,这样能够和以前使用requests的接口进行对接了app