动态创建方法

时间:2016-11-09 10:18:43

标签: python python-requests

我想知道是否有办法动态转换以下命令列表(列表实际上更长):

COMMANDS = {
"stop_scan" : ["get", "localhost:8090/stop"],
"send_url_to_spider" : ["post", "localhost:8090/spider", "baseUrl"],
"get_scanner_status" : ["get","localhost:8090/scanner/status"]}

进入我的Request课程'方法。

class RequestFactory(requests.Request):

    def __init__(self):
        super().__init__()

    def magic_happens():
        return
只需输入:

即可
scanner = RequestFactory()
scanner.stop_scan() #will perform Requests("GET", "localhost:8090/stop"]")

我知道我可以输入命令作为方法,但这不是重点。命令列表大约有30-40行,我希望有一种工厂类型方法,将命令中的字符串转换为实际的请求

1 个答案:

答案 0 :(得分:2)

这就是我所得到的(不要忘记将http://添加到您的网址中):

import requests

COMMANDS = {
    "stop_scan": ["get", "http://localhost:8090/stop"],
    "send_url_to_spider": ["post", "http://localhost:8090/spider", "baseUrl"],
    "get_scanner_status": ["get", "http://localhost:8090/scanner/status"]}


class RequestFactory(requests.Request):
    def __init__(self):
        super().__init__()


def get_method(request_params):
    def method(self):
        data = None
        if len(request_params) == 3:
            data = request_params[2]
        resp = requests.request(request_params[0], request_params[1], data=data)
        return resp

    return method


for method_name, request_params in COMMANDS.items():
    setattr(RequestFactory, method_name, get_method(request_params))

fac = RequestFactory()
fac.stop_scan()
fac.send_url_to_spider()
fac.get_scanner_status()