问题
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