hyper發送表單數據

前言

某個美麗的下午,運維把服務器上的nginx升級了,http協議也變成了http2.0,我本地的requests再也鏈接不到服務器,而後就找到了額hyperhtml

可是hyper的文檔寫的很簡單,並且相比requests來講還沒那麼人性化,看着demo說吧python

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模塊nginx

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的接口進行對接了app

相關文章
相關標籤/搜索