testing_kate testing_kate - 27 days ago 21
Python Question

Dynamically create methods

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

COMMANDS = {
"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
Request
class' methods.

class RequestFactory(requests.Request):

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

def magic_happens():
return


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

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

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__()


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()
fac.stop_scan()