【Python】接口測試工具方法 - 將string格式的header轉換爲dict

背景

在測試過程中,我們可能拿到一個接口的header或者body,需要將其作爲測試的參數去使用,再python裏,需要給key和value加上引號,這個操作很麻煩,希望有個方法能幫我直接格式化。

代碼

將帶有換行的,用冒號分割的string格式化爲dict

def string_lines_to_dict(str_lines):
    """
    將一個多行的String內容轉化爲dict或是json格式
    場景是我們對接口中header進行快速修改時需要加各種引號什麼的,費時,該方法迅速處理

    str_lines:(example)
            Accept: application/json, text/javascript, */*; q=0.01
            Accept-Encoding: gzip, deflate
            Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7
            Connection: keep-alive
            Content-Length: 18
            Content-Type: application/x-www-form-urlencoded; charset=UTF-8
            Cookie: sw_uuid=9651673088; ssuid=2745194500; SUID=C7936E246920A00A000000005EA56D84; 
            Host: clbwiki.wenwen.sogou.com
            Origin: http://test.com
            Referer: http://test.com/info/66
            User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36
            X-Requested-With: XMLHttpRequest

    無需錯誤處理,這樣能保留元數據是否錯誤

    :param str_lines: 直接從瀏覽器中直接copy過來的header內容 或其他信息: 其中必須有回車後
    :return: 可以用於request的header或者body
    """
    if str_lines is None or str_lines.strip() == "":
        return None

    lines = str_lines.split("\n")
    if len(lines) < 1:
        assert 'str_lines 必須包含換行'
    str_dict = {}
    for i in lines:
        i = i.strip()
        if i is not None and i != "":
            str_list = i.split(":", 1)
            length = len(str_list)
            if length > 2:
                str_dict[str_list[0]] = ":".join(str_list[1:])
            elif length == 2:
                str_dict[str_list[0]] = str_list[1].strip()
            else:
                assert "data is data, cant be dict"
                return None
    return str_dict

將用&拼接的含=的string格式化爲dict

def string_to_dict(line_str):
    """
    這個主要是處理接口中的post方式的body數據

    line_str:(example)
        wiki_id=1781&raw=1

    無需錯誤處理,這樣能保留元數據是否錯誤

    :param line_str:
    :return:
    """
    if line_str is None or line_str.strip() == "":
        return None
    tmp = line_str.split('?', 1)
    if len(tmp) > 1:
        line_str = tmp[1]
    str_dict = {}
    for i in line_str.split("&"):
        i = i.strip()
        if i is not None and i != "":
            str_list = i.split("=")
            # 使用urllib.unquote()對ascll的url參數進行解碼
            # (url的編碼格式採用的是ASCII碼,而不是Unicode,這也就是說你不能在Url中包含任何非ASCII字符,
            # 例如中文。否則如果客戶端瀏覽器和服務端瀏覽器支持的字符集不同的情況下,中文可能會造成問題。)
            try:
                str_dict[str_list[0]] = parse.unquote(str_list[1].strip())
            except IndexError as e:
                assert "Confirm your data: " + str(e)
                return None
    return str_dict

測試

if __name__ == '__main__':
    strs = """
        Accept: application/json, text/javascript, */*; q=0.01
        Accept-Encoding: gzip, deflate
        Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7
        Connection: keep-alive
        Content-Length: 18
        Content-Type: application/x-www-form-urlencoded; charset=UTF-8
        Cookie: sw_uuid=9651673088; ssuid=2745194500; SUID=C7936E246920A00A000000005EA56D84; 
        Host: clbwiki.wenwen.sogou.com
        Origin: http://test.sogou.com
        Referer: http://test.com/info/66
        User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36
        X-Requested-With: XMLHttpRequest
        """

    print(string_lines_to_dict(strs))

    print(string_to_dict("wiki_id=1781&raw=1"))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章