在python dict中使用字符串值时如何避免KeyError

时间:2019-12-12 16:48:13

标签: python dictionary header dropbox

我正在使用Dropbox api上传这样的文件:

token = 'This is the token'
file_name = 'This is the file_name'
headers = {
    "Authorization": "Bearer {}".format(token),
    "Content-Type": "application/octet-stream",
    "Dropbox-API-Arg": "{\"path\":\"/my/path/my-file-name\",\"mode\":{\".tag\":\"overwrite\"}}"
}
data = open("my-file-name", "rb").read()

r = requests.post(url, headers=headers, data=data)

问题在于,每当我运行此文件时文件名都会更改,因此我需要执行以下操作:

headers = {
    "Authorization": "Bearer {}".format(token),
    "Content-Type": "application/octet-stream",
    "Dropbox-API-Arg": "{\"path\":\"/my/path/{}\",\"mode\":{\".tag\":\"overwrite\"}}".format(file_name)
}

但是当我这样做时,我收到错误消息:

Traceback (most recent call last):
  File "headertest.py", line 6, in <module>
    "Dropbox-API-Arg": '{"path":"/my/path/{}","mode":{".tag":"overwrite"}}'.format(file_name)
KeyError: '"path"'

2 个答案:

答案 0 :(得分:2)

使用 .format 时,您需要将应该在字符串中的赞誉加倍,例如:{{}}。基本上{{等价于反斜杠,以引起引号,例如:\“。您的代码应如下所示:

s = '{{\"path\":"/my/path/{}","mode":{{".tag":"overwrite"}}}}'.format(file_name)

答案 1 :(得分:2)

您已将{}嵌套在json字符串中。您应该首先创建一个普通的dict并将file_name放入其中。然后json.dumps()放入标头字典中。

import json

token = 'abc'
file_name = 'This is the file_name'
arg_dict = {"path":"/my/path/{}".format(file_name),"mode":{"tag":"overwrite"}}
arg_s = json.dumps(arg_dict)

headers = {
    "Authorization": "Bearer {}".format(token),
    "Content-Type": "application/octet-stream",
    "Dropbox-API-Arg": arg_s
}

print(headers)

输出:

{'Authorization': 'Bearer abc', 'Content-Type': 'application/octet-stream', 'Dropbox-API-Arg': '{"path": "/my/path/This is the file_name", "mode": {"tag": "overwrite"}}'}