首页 > 解决方案 > 在 Django 管理命令中读取文件

问题描述

我正在尝试使用 gspread 读取 Google Sheets API 的凭据。我写了以下代码:

class Command(BaseCommand):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def handle(self, *args, **kwargs):
        scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']

        credentials = ServiceAccountCredentials.from_json_keyfile_name('/static/json/spreadsheets.json', scope)

        gc = gspread.authorize(credentials)

        wks = gc.open("Where is the money Lebowski?").sheet1

        self.stdout.write(self.style.SUCCESS('Succesfully ran "sheets" command'))

读取文件返回以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'static/json/spreadsheets.json'

我尝试了多种路径,例如:

但似乎没有一个工作。有人可以帮我吗?

标签: pythondjango

解决方案


当您使用绝对路径时,它是从字面上获取的,即从文件系统的根目录开始,即/.

当您使用相对路径时,即没有/在启动时,它是从调用脚本的目录解析的,而不是脚本实际位于文件系统中的位置。

所以当你通过 eg 调用 Django 管理命令时./manage.py <command>,它会查找从manage.pyie的当前目录开始的路径os.path.dirname('manage.py')。如果您将路径指定为static/json/spreadsheets.json,则它查找的完整路径为:

os.path.join(
    os.path.abspath(os.path.dirname('manage.py')),
    '/static/json/spreadsheets.json'
)

因此,您需要确保该spreadsheets.json文件位于正确的目录中。更好的方法是对这些场景使用绝对路径。如果你在 GNU/Linux 上,你可以使用:

readlink -f static/json/spreadsheets.json

获取绝对路径。


此外,您应该将文件作为管理命令的参数,而不是对文件进行硬编码。Django 管理命令argparse用于参数解析,因此您可以查看文档


推荐阅读