在一个实例中使用Python变量

2024-10-03 02:44:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我所要做的只是在我的“scanjob”变量中使用第二个变量,再加上“api\u tok”。我正在使用一个产品,它需要为每个调用使用一个api\u令牌,所以我只想在需要的地方持续添加“api\u tok”。到目前为止

auths = requests.get('http://10.0.0.127:443', auth=('admin', 'blahblah'), headers = heads)
api_tok = {'api_token=e27e901c196b8f0399bc79'}
scanjob = requests.get('http://10.0.0.127:4242/scanjob/1?%s'  % (api_tok))
scanjob.url
u"http://10.0.0.127:4242/scanjob/1?set(['api_token=e27e901c196b8f0399bc79'])"

从scanjob.url可以看到,它在“?”之后添加了一个“set”。为什么?如果我能去掉那个“设置”,我的电话就行了。我尝试了许多不同的组合字符串的变体,例如:

scanjob = requests.get('http://10.0.0.127:4242/scanjob/1?%s' + api_tok)
scanjob.url
u"http://10.0.0.127:4242/scanjob/1?set(['api_token=e27e901c196b8f0399bc79'])"
scanjob = requests.get('http://10.0.0.127:4242/scanjob/1?' + str(api_tok))
scanjob.url
u"http://10.0.0.127:4242/scanjob/1?set(['api_token=e27e901c196b8f0399bc79'])"

什么


Tags: tokenauthapihttpurlgetadmin产品
1条回答
网友
1楼 · 发布于 2024-10-03 02:44:52

{....}是生成set object的语法:

As of Python 2.7, non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: {'jack', 'sjoerd'}, in addition to the set constructor.

例如:

>>> {'api_token=e27e901c196b8f0399bc79'}
set(['api_token=e27e901c196b8f0399bc79'])
>>> {'jack', 'sjoerd'}
set(['jack', 'sjoerd'])

这就是你的神秘文本的来源

你只想在这里产生一个字符串:

api_tok = 'api_token=e27e901c196b8f0399bc79'
scanjob = requests.get('http://10.0.0.127:4242/scanjob/1?%s'  % api_tok)

或者,告诉requests使用params关键字参数添加查询参数,并传入字典:

parameters = {'api_token': 'e27e901c196b8f0399bc79'}
scanjob = requests.get('http://10.0.0.127:4242/scanjob/1', params=parameters)

这样做还有一个额外的优点,requests现在负责正确地编码查询参数

相关问题 更多 >