简体   繁体   English

python脚本上的KeyError

[英]KeyError on python script

I have this script to delete files from my slack account: 我有以下脚本从我的备用帐户中删除文件:

import requests
import json
import calendar
import re
from datetime import datetime, timedelta

_token = re.escape("token")
_domain = re.escape("domain")

if __name__ == '__main__':
    while 1:
        files_list_url = 'https://slack.com/api/files.list'
        date = str(calendar.timegm((datetime.now() + timedelta(-30))
            .utctimetuple()))
        data = {"token": _token, "ts_to": date}
        response = requests.post(files_list_url, data = data)

        if len(response.json()["files"]) == 0:
            break
        for f in response.json()["files"]:
            print "Deleting file " + f["name"] + "..."
            timestamp = str(calendar.timegm(datetime.now().utctimetuple()))
            delete_url = "https://" + _domain + ".slack.com/api/files.delete?t=" + timestamp
            requests.post(delete_url, data = {
                "token": _token, 
                "file": f["id"], 
                "set_active": "true", 
                "_attempts": "1"})
    print "DONE!"

Im getting this error: 我收到此错误:

File "main.py", line 28, in files = json.loads(content)["files"] KeyError: 'files' 文件“ main.py”,第28行,在files = json.loads(content)[“ files”] KeyError:'files'

Am i missing something? 我想念什么吗? Tks! Tks!

Switch 开关

if len(response.json()["files"]) == 0:

To

if len(response.json().get("files", [])) == 0:

By default, the get method returns None if the attribute doesn't exist, whereas the [] notation throws up an error if the item doesn't exist. 默认情况下,如果属性不存在,则get方法将返回None ,而如果该项不存在,则[]表示法将引发错误。 If the response.json() doesn't have a files attribute (which is what's happening here) then it will break out. 如果response.json()没有文件属性(此处正在发生),则它将崩溃。

You're expecting that json.loads() will return a dict that will have a key named files . 您期望json.loads()将返回一个包含名为files的键的字典。 But in reality, the parsed data doesn't have that key. 但实际上,解析的数据没有该密钥。

You can do these instead: 您可以改为:

payload = json.loads(content)
files = payload.get('files')

This way files will either contain the actual files as in the JSON payload. 这样, files将包含JSON有效内容中的实际文件。 If the files key does not exist, it will return None . 如果files密钥不存在,它将返回None

You can also pass a value to the get method to set the default value if the key is not found, like these: 如果未找到密钥,也可以将值传递给get方法以设置默认值,如下所示:

files = payload.get('files', [])

This way files will be an empty list if the files key doesn't exist. 这样,如果files键不存在,则文件将为空列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM