web自动化测试中根据headers原文raw构建requests通用参数

# -*-coding: utf-8 -*-

import requests
from . import request_headers


def construct_request_args(method,url,headers,proxies,data=None):
    """
    构造请求参数,主要是确定用 json=data 还是 data=data 还是params=data
    """
    request_args = {
        'method': method,
        'url': url,
        'headers': headers,
        'proxies': proxies,
        'verify': False
    }

    if data:                                            # 前提是有传入data
        if method.upper() == "GET":                     # 如果是GET请求,则用params
                request_args['params'] = data
        else:                                           # 如果不是GET请求,则看Content-Type
            content_type = headers.get('Content-Type')
            if content_type and 'json' in content_type: # Content-Type是'application/json',则用json
                request_args['json'] = data
            else:                                       # Content-Type是'multipart/form-data' 或者 'application/x-www-form-urlencoded',则用data
                request_args['data'] = data
    
    return request_args




class MyRobot:

    def __init__(self, Mobile, proxies=None):
        self.s = requests.Session()  # 每个account 新起一个session
        self.proxies = proxies
        self.Mobile = Mobile
        self.playload = None

    def getHeader(self,module):
        return request_headers.headerRawParse(module)
    

    def http_to(self,func_name):

        data = getattr(self.playload, func_name)  # 类型已经是dict

        method, url, headers = self.getHeader(func_name)
        request_args = construct_request_args(method=method, url=url, headers=headers, proxies=self.proxies, data=data)
        return self.s.request(**request_args)
# request_headers.py



my_func_name ='''
POST https://hello.abc.com/api/home/my_func_name HTTP/1.1
Host: hello.abc.com
Connection: keep-alive
Content-Length: 945
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/129.0.0.0
Accept: application/json, text/plain, */*
Content-Type: application/json
Origin: https://hello.abc.com
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: https://hello.abc.com/
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5
'''


my_func_name2 ='''
GET https://hello.abc.com/api/home/my_func_name2?a=123&b=456 HTTP/1.1
Host: hello.abc.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/129.0.0.0
Accept: application/json, text/plain, */*
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: https://hello.abc.com/
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5
'''





def headerRawParse(module):

    # header_raw = eval(module)
    header_raw = globals()[module]
    lines = header_raw.strip().split("\n")
    method = "GET"
    url = "https://baidu.com/"

    # 为了保持复制粘帖了不同版本的UA信息,此处统一定义
    UA = {}
    UA['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
    UA['sec-ch-ua'] = ''
    UA['sec-ch-ua-platform'] = ''
    UA['sec-ch-ua-mobile'] = '?0'
    uaKeys = UA.keys()


    headers = {}

    for line in lines:

        if len(line.strip()) == 0: continue
        if line.strip().split(" ", 1)[0].upper() in ["GET", "POST", "HEAD", "OPTIONS", "PUT", "PATCH", "DELETE"]:    # 提取 method 和 url
            method = line.strip().split(" ")[0].upper()
            url = line.strip().split(" ")[1]
            url=url.split("?")[0]       # 去掉get方法的url所带的参数
            continue
        if line.strip().split(" ", 1)[0].upper() in ["COOKIE:", "CONTENT-LENGTH:"]: continue    # 过滤掉(不要) COOKIE 和 CONTENT-LENGTH

        name_value = line.strip().split(": ")
        if len(name_value)>1:

            name, value = line.strip().split(": ",1)
            if name in uaKeys:                      # 为了保持复制粘帖了不同版本的UA信息,此处统一替换UA
                headers[name] = UA.get(name)
            else:
                headers[name] = value


        # {"method": method, "url": url, "headers": headers}
    return [method, url, headers]



if __name__ == "__main__":
    import re
    x=headerRawParse("xx")
    print(x[0],"\n",x[1],"\n",x[2])

# 参数模板

from .models import AccountBaseInfo

class RequestPlayloads():
    
    def __init__(self,Mobile):

        record = AccountBaseInfo.objects.get(Mobile=Mobile)

        self.func_name1 = {
            "xxx1": record.xxx1,
            "xxx2": "ccc",
            "xxx3": record.xxx3
        }

        self.func_name2= {
            "xxx1": "ccc",
            "xxx2": record.xxx2,
            "xxx3": "ccc"
        }

        self.func_name3= None    # 对于不带参数的GET请求,建议使用data值为None,而不是通过try来赋值None,这样可以避免有些必填的但遗漏却没有抛出Exception。



my_playload= RequestPlayloads('13888888888')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值