首页 > 解决方案 > 使用 python 3.6.3 从 Box.com 下载 excel 文件

问题描述

我已经阅读了很多帖子,但我仍然在努力解决一些问题。我正在尝试使用 python 脚本从 Box.com 下载 excel 文件文件到 cet os 文件夹。在这里,我使用 Box API 来下载文件。

#!/usr/bin/env python3

#import two classes from the boxsdk module - Client and OAuth2
from boxsdk import Client, OAuth2

# Define client ID, client secret, and developer token.
CLIENT_ID = None
CLIENT_SECRET = None
ACCESS_TOKEN = None

# Read app info from text file
with open('app.cfg', 'r') as app_cfg:
    CLIENT_ID = app_cfg.readline()
    CLIENT_SECRET = app_cfg.readline()
    ACCESS_TOKEN = app_cfg.readline().replace('\n', '')

#################################################


from boxsdk.network.default_network import DefaultNetwork
from pprint import pformat



class LoggingNetwork(DefaultNetwork):
    def request(self, method, url, access_token, **kwargs):
        """Base class override. Pretty-prints outgoing requests and incoming responses. """
        print('\x1b[36m{} {} {}\x1b[0m'.format(method, url, pformat(kwargs)))
        response = super(LoggingNetwork, self).request(
            method, url, access_token, **kwargs
        )
        if response.ok:
            print('\x1b[32m{}\x1b[0m'.format(response.content))
        else:
            print('\x1b[31m{}\n{}\n{}\x1b[0m'.format(
                response.status_code,
                response.headers,
                pformat(response.content),
            ))
        return response


###########################################

##########

# Create OAuth2 object. It's already authenticated, thanks to the developer token.
oauth2 = OAuth2(CLIENT_ID, CLIENT_SECRET, access_token=ACCESS_TOKEN)

# Create the authenticated client
client = Client(oauth2, LoggingNetwork())

#######################################################

items = client.folder(folder_id='0').get_items(limit=100, offset=0)
for item in items:
    with open('FileFromBox.xls', 'wb') as open_file:
        client.file(item.id).download_to(open_file)
        open_file.close()

我认为我已成功通过身份验证并获得了 file_id。执行此脚本后,将在主目录中创建文件,但这些文件不包含任何数据。我尝试执行 cat 命令,但没有显示数据。我确定文件放在 box.com 中。有人可以告诉我这段代码有什么问题吗?

标签: python

解决方案


推荐阅读