Search code examples
pythondictionaryheaderdropbox

How to avoid KeyError when using a string value in python dict


I am using the dropbox api to upload a file like this:

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)

The problem is that the file name will change whenever I run this so I would need to do something like:

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

But when I do this I receive the error:

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"'

Solution

  • You have nested {} inside your json string. You should create a plain dict first and put the file_name inside that. Then json.dumps() that into your header dict.

    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)
    

    Output:

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