简体   繁体   English

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

[英]What does this error mean and why does it happen?

In this code:在这段代码中:

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)

I am getting an error code related to one of the modules, which I do not know what it means.我收到与其中一个模块相关的错误代码,我不知道这意味着什么。 The error is:错误是:

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'

Why is this error code happening?为什么会出现此错误代码? Is there a way I can fix this, or is this a bug in the module?有没有办法解决这个问题,或者这是模块中的错误?

If I can fix it, how could I?如果我能修复它,我该怎么做?

there is no '_module' key in your data dict.您的数据字典中没有“_module”键。 Works for me using json authentication:使用 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)

then client is able to open worksheets, append rows, etc. Hope this helps然后客户端能够打开工作表,追加行等。希望这会有所帮助

you get this error cause you are not using the json format the oauth2client expects.您收到此错误是因为您没有使用oauth2client期望的 json 格式。 The module documentation of new_from_json says: new_from_json模块文档说:

class method new_from_json(json_data)[source] Utility class method to instantiate a Credentials subclass from JSON.类方法 new_from_json(json_data)[source] 从 JSON 实例化 Credentials 子类的实用类方法。

Expects the JSON string to have been produced by to_json().期望 JSON 字符串由 to_json() 生成。

Parameters: json_data – string or bytes, JSON from to_json().参数: json_data – 字符串或字节,来自 to_json() 的 JSON。

Returns: An instance of the subclass of Credentials that was serialized with to_json().返回: 使用 to_json() 序列化的 Credentials 子类的实例。

The key here is that it expects the json object you give it to be one that it produced as a serialised instance of the class.这里的关键是它期望你给它的 json 对象是它作为类的序列化实例生成的对象。 you cant just give it any arrbitrary json object and expect it to know what to do.你不能只是给它任何 arrbitrary json 对象并期望它知道该怎么做。

When you produce the JSON serialised credential object from the modules to_json method it will set the _module and _class data当您从模块to_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__

the reason this is important is later when you try to do new_from_json it will execute this part of the code这很重要的原因是稍后当您尝试执行new_from_json ,它将执行这部分代码


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

This fails in your case since the json you are using isnt json credential object produced by the module.这在您的情况下失败,因为您使用的 json 不是模块生成的 json 凭证对象。 The reson this is important is that later in the code it will need to know which service_account object to return to you这很重要的原因是,稍后在代码中需要知道要返回给您的 service_account 对象

    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)

Long story short you cant give this any old json and expect it to work you will need to first create your credentials object in the class then call its to_json method to then serialise that object to be able to use it later to just load credentials from storage.长话短说你不能给这个任何旧的 json 并期望它工作你需要首先在类中创建你的凭据对象然后调用它的 to_json 方法然后序列化该对象以便以后能够使用它来从存储加载凭据.

Using pydrive and oauth2client to authenticate, you can use the following:使用pydriveoauth2client进行身份验证,可以使用以下内容:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive    
from oauth2client.file import client


gauth = GoogleAuth()
cred = <content from `credentials.json`(string)>
gauth.credentials = client.Credentials.new_from_json(cred)
drive = GoogleDrive(gauth)

If you already have a credentials.json , there should not be a need for a client_secrets.json .如果您已经有credentials.json ,则不需要client_secrets.json

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

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