testing_kate testing_kate - 9 months ago 71
Python Question

Dynamically create methods

I'm wondering if there is a way to dynamically convert following list of commands (list is actually longer):

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

Into my
class' methods.

class RequestFactory(requests.Request):

def __init__(self):

def magic_happens():

by simply typing :

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

I know I can just type in the commands as methods, but that's not the point. The list of commands has around 30-40 lines and i'd like to have sort of a factory type method that converts the string in the commands into actual Requests

Answer Source

That is what I got (don't forget to add http:// to your urls):

import requests

    "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):

for method_name, request in COMMANDS.items():
    def method(self):
        data = None
        if len(request) == 3:
            data = request[2]
        resp = requests.request(request[0], request[1], data=data)
        return resp

    setattr(RequestFactory, method_name, method)

fac = RequestFactory()