繁体   English   中英

从 Firebase 存储桶下载 CSV 文件 - Python

[英]Download CSV file from Firebase Bucket Storage - Python

我有一个 CSV 文件,每天在 Firebase 存储桶中上演。 我想每天将这个更新的 CSV 文件下载到我的本地机器上。

使用以下 Python 代码,我可以生成一个链接,我可以在其中单击并下载文件。 但是,我想知道是否可以下载它而无需单击生成的链接。

import datetime
import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage

### Fetch the service account key JSON file contents
cred = credentials.Certificate("SDK_key.json")

### Initialize the app with a service account, granting admin privileges
app = firebase_admin.initialize_app(cred, {'storageBucket': 'XYZ.appspot.com',}, name='storage')

bucket = storage.bucket(app=app)

### Address of file to downloaded
blob = bucket.blob("test.csv")

### Generate a link and clicking on the link downloads the file
print(blob.generate_signed_url(datetime.timedelta(seconds=300), method='GET'))

我想你会在这里找到你的答案。

@James Daniels 指出getSignedURL()是检索指定文件的关键组件,但您可以使用 Firebase Admin SDK (充当谷歌云存储 SDK 的包装器)来实现。

示例代码

  • 您不需要 firebase-admin SDK 下载公开可见的文件
  • 确保您使文件夹位置可见,否则您需要附加访问令牌,该令牌只能通过客户端 sdk 获取。

示例 Firebase 安全规则

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
     // Explicitly define rules for the 'publicpath' pattern
    match /publicpath/{allPaths}{
      allow  write: if request.auth != null;    // Only auth users can write
      allow  read: if request.auth == null;   //Publically Readable
    }
    // This will be defined for everything else
    match /{allPaths=**} {
      allow  write: if request.auth != null;  // Only auth users can write
      allow  read: if request.auth != null;  // Only auth users can read
    }
  }
}

Python 代码将文件另存为 CSV

使用 pandas,如果未安装,请使用 cmd 中的以下代码安装cmd

pip install pandas

样品 python 代码

import pandas as pd

def download_File(url):
    response = requests.get(url=url)
    path="downfile.csv"
    print(response)
    if response.status_code == 200:
        print("File Downloaded")

        df = pd.read_csv(url)   
        df.to_csv('outfile.csv')

        # with open('down.csv', 'w') as f:
        #     writer = csv.writer(f)
        #     for line in response.iter_lines():
        #         writer.writerow(line.decode('utf-8').split(','))
    else:
        print("Something went wrong")

def main:
    storageBucket='XYZ.appspot.com'
    # publicpath/test.csv should be changed to 
    # publicpath%2Ftest.csv

    bucket_path="publicpath%2Ftest.csv"
    firebase_storageURL = 'https://firebasestorage.googleapis.com/v0/b/{}/o/{}?alt=media'.format(storageBucket, bucket_path)

    download_File(firebase_storageURL)


#Main program
if __name__ == '__main__':
    main()

记得更新firebase存储规则


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM