Reputation: 4199
I need to make several requests, using either get
or post
method, I want to write the requests into one statement like
response = getattr(requests, method)(url, parameters)
when method == 'get'
, Above should work as response = getattr(requests, method)(url, params=parameters)
, when method == 'post'
, it should work as response = getattr(requests, method)(url, json=parameters)
Upvotes: 0
Views: 38
Reputation: 1
params = xxx
json =yyy
if method == 'GET':
response = getattr(requests, method)(url, parameters = params)
elif method == 'POST':
response = getattr(requests, method)(url, parameters = json)
Upvotes: 0
Reputation: 7141
You can rely on destructuring for something that doesn't look too terribly ugly.
response = getattr(requests, method)(url, **{('params' if method=='get' else 'json'):parameters})
Upvotes: 2
Reputation: 17408
def getattr(method):
if method == "get": return requests.get
elif method == "post": return requests.post
When you call getattr(method)
it will return a function object accordingly. Next you can call the returned function object accordingly.
response = getattr("get")(url, params=parameters)
translates to response = requests.get(url, params=parameters)
Upvotes: 0