这个错误是什么意思?为什么会发生?

2024-10-01 22:28:16 发布

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

在此代码中:

import requests, pprint, re, gspread, time
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime
import oauth2client, httplib2
from oauth2client.file import Storage



def temperature():
    scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
    storage = oauth2client.file.Storage('Singapore-Weather-84def2be176a.json')
    credentials = storage.get()
    http = httplib2.Http()
    http = credentials.authorize(http)
    credentials.refresh(http)
    gc = gspread.authorize(credentials)

    wks = gc.open('Singapore Weather').sheet1
    r = requests.get('https://api.darksky.net/forecast/b02b5107a2c9c27deaa3bc1876bcee81/1.312914,%20103.780257')
    json_object = r.json()


    regexCurrentTemp = re.compile(r'"temperature":(\d\d.\d\d)')
    moTemp = regexCurrentTemp.search(str(json_object))
    temperature = moTemp.group(1)

    regexApparentTemp = re.compile(r'"apparentTemperature":(\d\d.\d\d)')
    moApparent = regexApparentTemp.search(str(json_object))
    apparent = moApparent.group(1)

    current = json_object['currently']
    cloud = current['cloudCover']
    cloud *= 100

    timenow = datetime.now()
    wks.append_row([str(timenow), temperature, apparent, cloud])

while True:
    temperature()
    time.sleep(3597)

我得到了一个与其中一个模块相关的错误代码,我不知道这是什么意思。错误是:

Traceback (most recent call last):
  File "/Users/rosen59250/PycharmProjects/MorningWeather/main.py", line 39, in <module>
    temperature()
  File "/Users/rosen59250/PycharmProjects/MorningWeather/main.py", line 12, in temperature
    credentials = storage.get()
  File "/Users/rosen59250/EvenorOdd/lib/python3.7/site-packages/oauth2client/client.py", line 407, in get
    return self.locked_get()
  File "/Users/rosen59250/EvenorOdd/lib/python3.7/site-packages/oauth2client/file.py", line 54, in locked_get
    credentials = client.Credentials.new_from_json(content)
  File "/Users/rosen59250/EvenorOdd/lib/python3.7/site-packages/oauth2client/client.py", line 302, in new_from_json
    module_name = data['_module']
KeyError: '_module'

为什么会出现这种错误代码?有没有办法解决这个问题,或者这是模块中的一个错误

如果我能修好它,我怎么能修好呢


Tags: infrompyimportjsonhttpgetobject
2条回答

出现此错误是因为您没有使用oauth2client所期望的json格式。{}的{a1}表示:

class method new_from_json(json_data)[source] Utility class method to instantiate a Credentials subclass from JSON.

Expects the JSON string to have been produced by to_json().

Parameters: json_data – string or bytes, JSON from to_json().

Returns: An instance of the subclass of Credentials that was serialized with to_json().

这里的关键是,它希望您给它的json对象是它作为类的序列化实例生成的对象。您不能只给它任何arrbitrary json对象,然后期望它知道该做什么

当您从modulesto_json方法生成JSON序列化凭证对象时,它将设置_module_class数据


        # Add in information we will need later to reconstitute this instance.
        to_serialize['_class'] = curr_type.__name__
        to_serialize['_module'] = curr_type.__module__

这一点很重要的原因是,当您稍后尝试执行new_from_json时,它将执行这部分代码


        # Find and call the right classmethod from_json() to restore
        # the object.
        module_name = data['_module']

在您的情况下,这会失败,因为您使用的json不是模块生成的json凭证对象。这一点很重要的原因是,在代码的后面,它需要知道要返回给您的服务帐户对象

    def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client import service_account
        data = json.loads(_helpers._from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
                data['_class'] == 'ServiceAccountCredentials'):
            return service_account.ServiceAccountCredentials.from_json(data)
        elif (data['_module'] == 'oauth2client.service_account' and
                data['_class'] == '_JWTAccessCredentials'):
            return service_account._JWTAccessCredentials.from_json(data)

长话短说,你不能给它任何旧的json并期望它工作。你需要首先在类中创建你的凭证对象,然后调用它的to_json方法,然后序列化该对象,以便以后能够使用它从存储中加载凭证

您的数据目录中没有“_module”密钥。使用json身份验证对我有效:

pass_url='/my/json/pass.json'
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name(pass_url, scope)
client = gspread.authorize(creds)

然后,客户端可以打开工作表、追加行等。 希望这有帮助

相关问题 更多 >

    热门问题