• hyper发送表单数据


    前言

    某个美丽的下午,运维把服务器上的nginx升级了,http协议也变成了http2.0,我本地的requests再也连接不到服务器,然后就找到了额hyper

    但是hyper的文档写的很简单,而且相比requests来说还没那么人性化,看着demo说吧

    hyper简单使用

    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模块

    requests模块中对data做了怎样的转换

    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发送表单数据了

    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的接口进行对接了

  • 相关阅读:
    MySQL数据库备份与还原
    MySQL的增、删、改、查
    MySQL与安全
    网址收集
    实现批量添加10个用户,用户名为user01-10,密码为user后面跟3个随机字符
    运维笔试Python编程题
    javascript 正则表达式 详细入门教程
    Web UI回归测试 -- BackstopJS 入门
    js 链接传入中文参数乱码解决
    项目搭建注意事项
  • 原文地址:https://www.cnblogs.com/wuyongqiang/p/10179535.html
Copyright © 2020-2023  润新知