Office365-rest-python-client: 如何访问名称中带有特殊字符的服务器上的远程文件?

创建于 2021-01-13  ·  5评论  ·  资料来源: vgrem/Office365-REST-Python-Client

我正在使用您的 Python 客户端从 SharePoint 文件夹下载文件。 这基本上有效,但是,某些文件具有不常见的名称(带有特殊字符),并且下载不起作用。 例如,典型的此类文件名将是Sequenz%2001.mp4#t=0.033333.jpg - 未编码,文件名正是如此。

当我尝试以该名称访问该文件时,出现“找不到文件”错误。 但是当我将文件重命名为test.jpg ,下载工作。 我正在按照您的示例下载文件:

FILE = "/Sequenz%2001.mp4#t=0.033333.jpg"  # it does work with "test.jpg" here
# Some more constants for USER, PASS, URL, etc.

ctx_auth = AuthenticationContext(URL)
if ctx_auth.acquire_token_for_user(USER, PASS):
    ctx = ClientContext(URL + SITE, ctx_auth)
    local_file_name = "/tmp" + FILE
    try:
        with open(local_file_name, "wb") as local_file:
            f = ctx.web.get_file_by_server_relative_url(SITE + PATH + FILE)
            f.download(local_file).execute_query()
    except ClientRequestException:
        print("Can't fetch remote file: " + PATH + FILE)

我试图通过urllib.parse.quote()引用文件名并使用它,但结果相同。
我需要什么才能访问这样的文件?

enhancement

所有5条评论

@haimat您是否尝试过对 url 进行 urlencoding?

import urllib
FILE = urllib.parse.urlencode("/Sequenz%2001.mp4#t=0.033333.jpg")

如果这不起作用,请尝试urllib.parse.quote_plus

@xibriz谢谢,但不幸的是,这并不能为我解决。
我试过quote_plus() ,但没有运气(函数urlencode()用于键/值对,所以不适用于我这里的用例)。

任何人都可以重现这个问题吗?

@haimat我能够重现错误并修复问题,但@vgrem应该荣幸地提出永久修复。

以下类负责处理特殊字符:
https://github.com/vgrem/Office365-REST-Python-Client/blob/4bf8ee0b65985980b50fc3b74b32fd2db34561ba/office365/runtime/odata/odata_path_parser.py#L6

下载文件的代码似乎是正确的:
https://github.com/vgrem/Office365-REST-Python-Client/blob/1d7f3d90c17cdbbe9d2b27990e0fe657a2100da9/office365/sharepoint/actions/download_file.py#L30

但是由于某些原因,下载文件时没有使用getFileByServerRelativePath ,而是getFileByServerRelativeUrl
https://github.com/vgrem/Office365-REST-Python-Client/blob/1d7f3d90c17cdbbe9d2b27990e0fe657a2100da9/office365/sharepoint/webs/web.py#L202

将该文件中的第 202 行更改为ResourcePathServiceOperation("getFileByServerRelativePath", [url], self.resource_path)
并对 odata_path_parser.py 进行以下更改可以解决问题,但不是正确的解决方法。

elif method_parameters is not None:
            url += "(decodedurl="

@xibriz
您的修复/解决方法确实为我解决了这个问题,我现在可以访问这些文件。
非常感谢,你救了我的一天!

@haimat欢迎您😊

@vgrem您应该将标签更改为 bug

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

continda picture continda  ·  4评论

Cesaaar picture Cesaaar  ·  7评论

ahulist picture ahulist  ·  5评论

Mark531 picture Mark531  ·  11评论

attibalazs picture attibalazs  ·  10评论