Reputation: 187
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
Upvotes: 1
Views: 69
Reputation: 12140
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__()
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()
Upvotes: 2