I have the following code for making a RESTful call to a server:
def request(self, request, account_id, user):
if request is 'get_id':
#Get user from id
result = requests.get(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers)
elif request is 'get_username':
#Get user from username
result = requests.get(api_root + "/accounts/" + account_id + "/users?username=" + user, headers=self.headers)
elif request is 'get_email':
#Get user from username
result = requests.get(api_root + "/accounts/" + account_id + "/users?email=" + user, headers=self.headers)
elif request is 'post':
#Add user to new account
result = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers)
elif request is 'delete':
#Delete user from account
result = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers)
#Throw exception if non-200 response
result.raise_for_status()
#Print request result / status
print "\nRequest " + request + " Result: " + result.text + "\nStatus: " + str(result.status_code)
return result
I know this is ugly and I wanted to change it into a dictionary, something like:
def request(self, request, account_id, user):
url = api_root + "/accounts/" + account_id
function_dictionary = {}
function_dictionary['get_id'] = requests.get(url + "/users/" + user, headers=self.headers)
function_dictionary['get_username'] = requests.get(api_root + "/accounts/" + account_id + "/users?username=" + user, headers=self.headers)
function_dictionary['get_email'] = requests.get(api_root + "/accounts/" + account_id + "/users?email=" + user, headers=self.headers)
function_dictionary['delete'] = requests.delete(url + "/users/" + user, headers=self.headers)
function_dictionary['post'] = requests.post(url + '/users', data=json.dumps(user), headers=self.headers)
result = function_dictionary.get(request)
#Throw exception if non-200 response
result.raise_for_status()
return result
I still have a feeling I am going about it the wrong way. Can anybody tell me what the proper method to approach if / elseif statements in Python is?
Thanks!