我有一个看起来像这样的函数:
def request( request = None, account_id = 0, user_id = 0, user = {"ID":0}, headers = None):
"""Send a User request to the server
Send a request to the server
"""
url = api_root + "/accounts/" + str(account_id)
function_dictionary = {'get_user_from_id': (requests.get, #Function
(url + "/users/" + str(user_id),), #Tuple of Arguments
{'headers': headers}), #Dictionary of keyword args
'get_user_from_username': (requests.get,
(url + "/users?username=" + str(user_id),),
{'headers': headers}),
'get_user_from_email': (requests.get,
(url + "/users?email=" + str(user_id),),
{'headers': headers}),
'delete': (requests.delete,
(url + "/users/" + str(user_id),),
{'headers': headers}),
'patch_user':(requests.patch,
(url + "/users/" + str(user["ID"]),),
{'headers': headers, 'data':json.dumps(user)}),
'post': (requests.post,
(url + "/users" ,),
{'headers': headers,'data':json.dumps(user)})
}
func, args, kwargs = function_dictionary[request]
result = func(*args, **kwargs)
#Throw exception if non-200 response
result.raise_for_status()
#Result from query
print "Query " + request + " result: " + result.text
return result
是否可以从request
函数中删除此字典,以便每次调用请求时都不会重新构建该字典?
主要问题是 - 在调用函数时需要插入变量,即user_id, user, account_id
答案 0 :(得分:2)
不容易。
但我不知道你会这样做的原因。在每个请求上构建六项词典的开销是绝对无关紧要的。