0

I need a function that makes a http request (get, post etc) based on the input into the function without using a bunch of if statements

Eg. I have a function:

def http_request(URI, type, data=None):

    if type == "get":
        requests.get(URI)
    elif type == "post":
        requests.post(URI, data)

I want instead for the function to get more general and pass in 'get' or 'post' as functions so i wouldn't have to use if statements, like so:

def http_request(func, URI):

    r = requests.func(URI)

Needs to handle parameters for all types of http requests

Is this possible?

Thanks.

3 Answers3

0

If I understood you correctly:

class Request:
    def get(self):
        print("get")

    def post(self):
        print("post")

def get():
    return "get"

def post():
    return "post"



def http_request(func):
    request = Request()
    f = getattr(request, func())
    f()

http_request(get)
http_request(post)

Instead of the function get/post you can, of course, pass string directly.

See also: Calling a function of a module by using its name (a string)

Horus
  • 617
  • 7
  • 10
0

You could define functions in a dictionary and return the function:

def foo(x):
    return x

def bar(x):
    return 2*x

def wrapper(var, name):
    func_dict = {'foo':foo,
                 'bar':bar}
    if name in func_dict:
        print(func_dict[name](var))
        return func_dict[name](var)
    else:
        print('Method not implemented')
        
wrapper(3, 'foo')
wrapper(5, 'bar')
wrapper(10, 'baz')

This could also be defined as part of a class, using methods instead.

Dschoni
  • 3,714
  • 6
  • 45
  • 80
0

You can use the existing requests.request function:

import requests


def req(url, method="GET", *args, **kwargs):
    return requests.request(method, url, *args, **kwargs)

r = req("http://example.com")
r = req("http://example.com", method="POST", data="test")
HTF
  • 6,632
  • 6
  • 30
  • 49