无法使用 Graph API 将文件上传到 Sharepoint 网站。找不到资源

问题描述 投票:0回答:1

我可以看到驱动器中的文件,但在尝试写入时应该不存在。

这就是我查找文件的方式:

site_url = https://graph.microsoft.com/v1.0/sites
get_url = f"{site_url}/{site_id}/drives/{drive_id}/root/children"
headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json;odata.metadata=minimal",
    "Accept": "application/json;odata.metadata=minimal"
}
response = requests.get(get_url, headers=headers)
if response.status_code == 200:
    print(response.text)

并得到回复:

{
    "value": [
        {
            "createdDateTime": "2023-11-13T18:21:22Z",
            "lastModifiedDateTime": "2023-11-13T18:21:22Z",
            "name": "Reporte",
            "webUrl": "{site}/Shared%20Documents/Reporte",
        },
        {
            "@microsoft.graph.downloadUrl": "{download_url}",
            "name": "Open pip.txt"
        }
    ]
}

确认我可以访问驱动器, 但是当我尝试写入新文件时:

file_name = "Reporte Z.xlsx"
upload_url = f"{site_url}/{site_id}/drives/{drive_id}/root:/{file_name}:/content"

# Set headers
headers = {
    "Authorization": f"Bearer {access_token}",
    "Connection": "Keep-alive",
    "Content-Type": "text/plain"
}

# Read file content
with open(file_path, "rb") as file:
    file_content = file.read()

# Make POST request
response = requests.post(upload_url, headers=headers, data=file_content)

# Check response status
if response.status_code == 201:
    print("File uploaded successfully")
else:
    print("Error uploading file:", response.status_code, response.text)

我收到错误

Error uploading file: 404 {"error":{"code":"itemNotFound","message":"The resource could not be found.","innerError":{"date":"2023-11-13T18:47:51","request-id":"[string]","client-request-id":"[string]"}}}

我尝试删除根中的“:”,但获取实体仅允许使用 JSON Content-Type 标头进行写入。错误

我按照本教程(https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http)无济于事。

我查看了很多线程,但许多线程似乎从未找到解决方案。

python sharepoint python-requests microsoft-graph-api
1个回答
0
投票

我只需要从 POST 更改为 PUT。即使在教程中也是这么说的。

我会保留这个问题,以防其他人感到困惑。

来自:

# Make POST request
response = requests.post(upload_url, headers=headers, data=file_content)

致:

# Make PUT request
response = requests.put(upload_url, headers=headers, data=file_content)

我还将标题更改为:

headers = {
    "Authorization": f"Bearer {access_token}",
    "Accept": "application/json",
    "Content-Type": "text/plain"
}
© www.soinside.com 2019 - 2024. All rights reserved.