python - 在 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'
我尝试了多种路径,例如:
- '~/static/json/spreadsheets.json'
- '/json/电子表格.json'
- '电子表格.json'
但似乎没有一个工作。有人可以帮我吗?
解决方案
当您使用绝对路径时,它是从字面上获取的,即从文件系统的根目录开始,即/
.
当您使用相对路径时,即没有/
在启动时,它是从调用脚本的目录解析的,而不是脚本实际位于文件系统中的位置。
所以当你通过 eg 调用 Django 管理命令时./manage.py <command>
,它会查找从manage.py
ie的当前目录开始的路径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
用于参数解析,因此您可以查看文档。
推荐阅读
- c++ - 二维数组c ++中元素的出现次数
- python - Matplotlib:如何在 x 对数轴上显示并增加次要和主要刻度的大小
- java - Java、流、收集器、函数式编程:如何制作复式映射?
- php - Laravel hasMany 返回一个空数组或错误
- vba - 打开多个 PowerPoint 文件,导出到视频并关闭文件
- clickhouse - 在clickhouse中替换视图替代品?
- sql - 从列表中选择一个随机字符串会导致用 NULLS [SQL] 填充列
- java - 什么对计数、数组或哈希图(或集合)更有效
- youtube - youtube api - 获得波兰订阅最多的游戏频道
- wordpress - 如何使用 AWS Bitnami 让自定义子域在 Wordpress 上工作