![](/img/trans.png)
[英]How to Read .json file in python code from google cloud storage bucket
[英]Cannot read .json from a google cloud bucket
我在Google雲端存儲桶中有一個文件夾結構
bucket_name = 'logs'
json_location = '/logs/files/2018/file.json'
我嘗試使用此代碼在jupyter notebook
讀取此json
文件
from google.cloud import storage
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "logs/files/2018/file.json"
def download_blob(source_blob_name, bucket_name, destination_file_name):
"""Downloads a blob from the bucket."""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(source_blob_name)
blob.download_to_filename(destination_file_name)
print('Blob {} downloaded to {}.'.format(
source_blob_name,
destination_file_name))
然后調用函數
download_blob('file.json', 'logs', 'file.json')
我得到這個錯誤
DefaultCredentialsError: File /logs/files/2018/file.json was not found.
我已經看過所有關於stackoverflow的類似問題,但找不到解決方案。
json
文件存在,可以在Google雲存儲上的json_location中打開或下載。
GOOGLE_APPLICATION_CREDENTIALS
應該指向您正在運行jupyter的本地磁盤上的文件。 您需要憑據才能調用GCS,因此無法從GCS中獲取它們。
實際上,最好不要在程序中完全弄亂憑據,而要留給客戶端庫。 不要在我們的應用程序中觸摸GOOGLE_APPLICATION_CREDENTIALS
。 代替:
gcloud auth application-default login
。 然后,您的程序將自動使用您登錄時使用的任何帳戶。 在這里完整說明
關於您引用的json文件,有兩種不同的觀點:
1)用於向GCP進行身份驗證的json文件。
2)您要從存儲桶下載到本地計算機的json。
對於第一個,如果您要遠程訪問Jupyter服務器,則很可能json不存在於此類遠程計算機中,而是存在於本地計算機中。 如果您的情況是這樣,請嘗試將json上傳到Jupyter服務器。 在遠程計算機中執行ls -l /logs/files/2018/file.json
可以幫助驗證其正確性。 然后, os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "JSON_PATH_ON_JUPYTER_SERVER"
應該可以工作。
另一方面,我執行了您的代碼並得到:
>>> download_blob('static/upload_files_CS.png', 'bucketrsantiago', 'file2.json')
Blob static/upload_files_CS.png downloaded to file2.json.
文件gs://bucketrsantiago/static/upload_files_CS.png已下載到我的本地計算機,文件名為file2.json。 這有助於闡明唯一的問題與身份驗證json文件有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.