我正在尝试使用 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'
- '电子表格.json'
但似乎都不起作用。有人可以帮我吗?
最佳答案
当您使用绝对路径时,它是按字面意思理解的,即从文件系统的根目录开始,即 /
.
当您使用相对路径时,即没有 /
在开始时,它是从调用脚本的目录解析的,而不是脚本在文件系统中实际所在的目录。
因此,当您通过例如调用 Django 管理命令时./manage.py <command>
,它会查找从当前目录 manage.py
开始的路径即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
对于参数解析,你可以看一下 doc .
关于python - 在 Django 管理命令中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58715383/