Pass (optional) parameters to HTTP parameter (Python, requests)

有些话、适合烂在心里 提交于 2021-01-28 10:16:38

问题


I am currently working on an API Wrapper, and I have an issue with passing the parameters from a function, into the payload of requests. The parameters can be blockId, senderId, recipientId, limit, offset, orderBy. All parameters join by "OR". One possible solution could be having if statements for every combination, but I imagine that that is a terrible way to do it. (requests and constants are already imported)

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

What is (or are) more elegant ways to achieve parameters of the function getting passed to the requests payload?


回答1:


Shortest one:

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



回答2:


After tinkering around with Pythonist answer (which didn't work because there was always a NameError), I have come up with this solution:

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

As you can see, the important part is the payload:

payload = {name: kwargs[name] for name in kwargs if kwargs[name] is not None}

As long as there is a parameter (name) in the kwargs array and if it's value isn't None, it'll be added to the payload.



来源:https://stackoverflow.com/questions/46282018/pass-optional-parameters-to-http-parameter-python-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!