在Django管理命令中读取文件

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

我正在尝试使用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'

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

  • '〜/ static / json / spreadsheets.json'
  • '/ json / spreadsheets.json'
  • 'spreadsheets.json'

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

python django
1个回答
0
投票

[当您使用绝对路径时,它实际上是从文件系统的根目录开始,即/

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

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

因此,您需要确保在正确的目录中具有spreadsheets.json文件。更好的方法是针对此类情况使用绝对路径。如果您使用的是GNU / Linux,则可以使用:

readlink -f static/json/spreadsheets.json

获取绝对路径。

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


0
投票

首先:~符号在这种情况下不起作用,因为它只是一个* nix shell扩展为全路径的glob,因此在这种情况下它不能扩展,因为shell没有在这里演化。前导/符号会将您移至根目录。

我不知道所有情况(因为您没有提供有关运行此命令的目录以及与该目录相比文件的位置的信息。

但是您可以像这样使用getcwd库中的方法os

import os
print(os.getcwd())

或从调试器中了解您的当前位置。然后,您可以传递文件的绝对路径,或者根据需要使用“ ..”到达父目录,甚至可以使用os.chdir()方法更改当前工作目录,但是不建议这样做,因为它可能会对Django或Windows产生一些副作用。项目中使用的其他不希望目录在运行时更改的库。

© www.soinside.com 2019 - 2024. All rights reserved.