尝试使用C#客户端和Python获取Google电子表格的内容。
C#客户端运行正常,而python返回错误:
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://sheets.googleapis.com/v4/spreadsheets/IAD2okAWZD7anbt5L4ybgD2dxHBGmsY6IkNIWHBQkBM/values/new%20first%20sheet%21A1?alt=json returned "Requested entity was not found.">
如果我在浏览器中打开错误链接,则会看到错误:
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"status": "PERMISSION_DENIED"
}
}
Python客户端可能出什么问题了?
C#客户端:
private void button1_Click(object sender, EventArgs e)
{
string ApplicationName = "aaa";
UserCredential credential;
using (var stream =new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
String range = "new first sheet!A2:E";//mano
SpreadsheetsResource.ValuesResource.GetRequest request =service.Spreadsheets.Values.Get(spreadsheetId, range);
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
Console.WriteLine("Name, Major");
foreach (var row in values)
{
// Print columns A and E, which correspond to indices 0 and 4.
if (row.Count==1 ) Console.WriteLine("{0}", row[0]);
else
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
}
else
{
Console.WriteLine("No data found.");
}
Console.Read();
}
Python客户端:
class SS:
store = file.Storage('token.json')
try:
creds = store.get()
except Exception as e:
print(traceback.format_exc())
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))
# Call the Sheets API
SPREADSHEET_ID = 'IAD2okAWZD7anbt5L4ybgD2dxHBGmsY6IkNIWHBQkBM' #my
RANGE_NAME = 'new first sheet!A1' #my
def __init__(self):
print("Constructing")
def get(self):
print("starting get")
result = self.service.spreadsheets().values().get( spreadsheetId=self.SPREADSHEET_ID, range=self.RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[4]))