将(可选)参数传递给 HTTP 参数(Python、请求) [英] Pass (optional) parameters to HTTP parameter (Python, requests)

查看:117
本文介绍了将(可选)参数传递给 HTTP 参数(Python、请求)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发 API 包装器,但在将参数从函数传递到请求的有效负载时遇到问题.参数可以是blockId、senderId、recipientId、limit、offset、orderBy.所有参数通过OR"连接.一个可能的解决方案可能是对每个组合都有 if 语句,但我认为这是一种糟糕的方法.(请求和常量已经导入)

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?

推荐答案

在对 Pythonist 的答案(由于总是出现 NameError 没有奏效)进行修补后,我想出了这个解决方案:

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}

只要 kwargs 数组中有一个参数(名称)并且它的值不是 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.

这篇关于将(可选)参数传递给 HTTP 参数(Python、请求)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆