将(可选)参数传递给HTTP参数(Python,请求)

时间:2017-09-18 14:36:50

标签: python parameters python-requests parameter-passing

我目前正在开发一个API Wrapper,我遇到了将函数中的参数传递给请求的有效负载的问题。参数可以是blockId,senderId,recipientId,limit,offset,orderBy。所有参数都以“OR”连接。一种可能的解决方案可能是对每种组合使用if语句,但我认为这是一种可怕的方法。 (请求和常量已导入)

def transactionsList(*args **kwargs):
    if blockId not None:
        payload = {'blockId': blockId}
    if offset not None:
        payload = {'offset': offset}
    ...
    r = requests.get(constants.TRANSACTIONS_LIST, params=payload, timeout=constants.TIMEOUT)
    return r

实现传递给请求有效负载的函数参数的更优雅的方法是什么?

2 个答案:

答案 0 :(得分:0)

最短的一个:

PARAMS = ['blockid', 'senderid', 'recipientid', 'limit', 'offset', 'orderby']
payload = {name: eval(name) for name in PARAMS if eval(name) is not None}

答案 1 :(得分:0)

在修补Pythonist的答案后(由于总是存在NameError而无效),我提出了这个解决方案:

def __deepcopy__(self, memo):
    # Deepcopy only the id attribute, then construct the new instance and map
    # the id() of the existing copy to the new instance in the memo dictionary
    memo[id(self)] = newself = self.__class__(copy.deepcopy(self.id, memo))
    # Now that memo is populated with a hashable instance, copy the other attributes:
    newself.degree = copy.deepcopy(self.degree, memo)
    # Safe to deepcopy edge_dict now, because backreferences to self will
    # be remapped to newself automatically
    newself.edge_dict = copy.deepcopy(self.edge_dict, memo)
    return newself

如您所见,重要的部分是有效载荷:

def transactionsList(*args, **kwargs):
    payload = {name: kwargs[name] for name in kwargs if kwargs[name] is not None}
    r = requests.get(constants.TRANSACTIONS_LIST, params=payload, timeout=constants.TIMEOUT)
    # print(r.url)
    return r

只要kwargs数组中有一个参数(name),并且它的值不是None,它就会被添加到有效载荷中。