在一个实例中使用Python变量
我试图实现的是在我的“scanjob”变量中使用第二个变量,添加“api_tok”。我正在使用的产品需要为每个调用使用api_令牌,所以我只想在需要的地方持续添加“api_tok”。到目前为止在一个实例中使用Python变量,python,variables,Python,Variables,我试图实现的是在我的“scanjob”变量中使用第二个变量,添加“api_tok”。我正在使用的产品需要为每个调用使用api_令牌,所以我只想在需要的地方持续添加“api_tok”。到目前为止 auths = requests.get('http://10.0.0.127:443', auth=('admin', 'blahblah'), headers = heads) api_tok = {'api_token=e27e901c196b8f0399bc79'} scanjob = reque
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'])"
?
{….}
是生成以下内容的语法:
从Python2.7开始,除了集合
构造函数之外,还可以通过在大括号中放置逗号分隔的元素列表来创建非空集合(而不是冻结集合
),例如:{'jack',sjoerd'}
例如:
>>> {'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)
这还有一个额外的优点,请求
现在负责正确编码查询参数