Call function via literal name

Ian Kelly ian.g.kelly at gmail.com
Fri Jul 29 17:00:56 EDT 2016


On Fri, Jul 29, 2016 at 2:35 PM, TUA <kai.peters at gmail.com> wrote:
> Rather than do this:
>
>         if test['method'] == 'GET':
>                 res = requests.get(test['endpoint'],    auth=test['auth'], verify=False)
>         elif test['method'] == 'POST':
>                 res = requests.post(test['endpoint'],   auth=test['auth'], verify=False, json=test['body'])
>         elif test['method'] == 'PUT':
>                 res = requests.put(test['endpoint'],    auth=test['auth'], verify=False, json=test['body'])
>         elif test['method'] == 'DELETE':
>                 res = requests.delete(test['endpoint'], auth=test['auth'], verify=False)
>         elif test['method'] == 'HEAD':
>                 res = requests.head(test['endpoint'],   auth=test['auth'], verify=False)
>
> I would like to call the requests method that corresponds to test['method'] by finding that function by name - how can I achieve that?

getattr(requests, test['method'].lower())(test['endpoint'],
auth=test['auth'], verify=False)

For security, if the input is not trusted you should also do
validation that the method is one that you expect, e.g.:

if test['method'] not in {'GET', 'POST', 'PUT', 'DELETE', 'HEAD'}:
    raise ValueError("Received unexpected method %s" % test['method'])

If you want to conditionally pass the json argument then pass it as a
** argument, e.g.:

kwargs = {
    'auth': test['auth'],
    'verify': False,
}
if test['method'] in ('POST', 'PUT'):
    kwargs['json'] = test['body']
getattr(requests, test['method'].lower())(test['endpoint'], **kwargs)



More information about the Python-list mailing list