无法从内部文件夹、OneDrive、Microsoft Graph、Python 下载文件文件夹、文件、OneDrive、Microsoft

2023-09-07 09:04:55 作者:姑娘,你真是美得不像话

我正在尝试使用 microsoft graph api 从 onedrive 下载文件,我在文件夹新文件夹"中有名为Knox EARNSTSALV2020.xlsx"的文件,但出现错误,我可以从文件夹外部下载文件.

I am trying to download files from onedrive using microsoft graph api, I have File named "Knox EARNSTSALV2020.xlsx" inside Folder "New Folder", but I am getting error, I can download file from outside of the folder.

错误:

b'{
  "error": {
    "code": "itemNotFound",
    "message": "Item not found",
    "innerError": {
      "request-id": "8c4f973a-cd22-48eb-bdfd-f5eb8a051389",
      "date": "2020-05-09T10:55:40"
    }
  }
}'

代码参考:使用 Python 从个人 OneDrive 下载文件

import sys, os, time, requests
import pandas as pd
import urllib.parse

OneDrive_FilePath = 'New Folder/Knox EARNSTSALV2020.xlsx'

OneDrive_FileURL = 'https://graph.microsoft.com/v1.0/me/drive/root:/' + OneDrive_FilePath + ':/content'
OneDrive_FileURL = urllib.parse.quote(OneDrive_FileURL, safe=':/')
print(OneDrive_FileURL)

Client_Id = 'XXXX'
Tenant_Id = 'YYYYY'
Refresh_Token_First = 'ZZZZZ'

PostStr = {'grant_type': 'refresh_token', 'client_id': Client_Id, 'refresh_token': Refresh_Token_First}

Token_Response = requests.post('https://login.microsoftonline.com/' + Tenant_Id + '/oauth2/v2.0/token', data=PostStr)

Access_Token = Token_Response.json()['access_token']
New_Refresh_Token = Token_Response.json()['refresh_token']

if Access_Token is None or New_Refresh_Token is None:
    print('
> Failed: Access_Token NOT Retrieved')
    sys.exit()

Response = requests.get(OneDrive_FileURL, headers={'Authorization': 'Bearer ' + Access_Token})

if Response.status_code == 200:
    print('
> Response Success')

    with open('Excel File.xlsx', 'wb') as File:
    File.write(Response.content)
    print('
> File Downloaded')
else:
    print('
> Failed:', Response.status_code)
    print(Response.content)

推荐答案

我的路径中也有空格,我不使用 urllib.parse.quote.尝试使用以下命令调用 get 请求:https://graph.microsoft.com/v1.0/me/drive/root:/New Folder/Knox EARNSTSALV2020.xlsx:/content

I also have spaces in my path and I don't use urllib.parse.quote. Try to call the get request with: https://graph.microsoft.com/v1.0/me/drive/root:/New Folder/Knox EARNSTSALV2020.xlsx:/content