向 API 请求添加可选参数的 Pythonic 方式
我正在尝试发出一个 API 请求,在其中添加一些可选值,但如果我不添加它们,我不希望它们出现在请求中。
在这种情况下,我希望参数为 'startblock' & 'endblock'
def get_transactions_by_address_(self, address, action='txlist'):
"""
:param address:
:param action: [txlist, txlistinternal]
:return:
"""
token = self.etherscan_api_key
return requests.get('https://api.etherscan.io/api'
'?module=account'
f'&action={action}'
f'&address={address}'
# '&startblock=0'
# '&endblock=92702578'
'&page=1'
'&offset=1000'
'&sort=desc'
f'&apikey={token}'
)
我正在考虑添加一些条件,例如
request_url = 'https://api.etherscan.io/api...'
if startblock:
request_url = request_url + f'&startblock={startblock}'
if endblock:
request_url = request_url + f'&endblock={endblock}'
但我不知道这是否是最Pythonic的方式来做到这一点,我想获得有关如何做到这一点的其他选项
I'am trying to make an API request where I add some optional values but if I don't add them I don't want them to be in the request.
In this case, I would like the parameters to be 'startblock' & 'endblock'
def get_transactions_by_address_(self, address, action='txlist'):
"""
:param address:
:param action: [txlist, txlistinternal]
:return:
"""
token = self.etherscan_api_key
return requests.get('https://api.etherscan.io/api'
'?module=account'
f'&action={action}'
f'&address={address}'
# '&startblock=0'
# '&endblock=92702578'
'&page=1'
'&offset=1000'
'&sort=desc'
f'&apikey={token}'
)
I was thinking on adding some conditionals like
request_url = 'https://api.etherscan.io/api...'
if startblock:
request_url = request_url + f'&startblock={startblock}'
if endblock:
request_url = request_url + f'&endblock={endblock}'
But I don't know if it is the most pythonic way to do it and I would like to get other options on how to do it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
payload
选项而不是自己构建 URL。例如,创建一个包含所有必需选项的dict
,然后根据需要向该字典添加其他参数。requests.get
将从基本 URL 和dict
中找到的值构建所需的 URL。Use the
payload
option instead of constructing the URL yourself. For example, create adict
containing all the required options, then add additional parameters to the dict as necessary.requests.get
will build the required URL from the base URL and the values found in yourdict
.正确的实现方法是:
The correct way to implement is: