【问题标题】:Flask: How to upload a user file into Google Cloud Storage using upload_blobFlask:如何使用 upload_blob 将用户文件上传到 Google Cloud Storage
【发布时间】:2022-01-04 21:50:23
【问题描述】:

我正在使用 Flask 制作一个 Web 应用程序,并且我想将用户输入文件上传到 Google Storage Cloud。我正在使用 Heroku 托管我的网络应用程序,但我不知道如何将文件保存在 Heroku 的临时存储中,因此我尝试使用 tempfile 将文件存储在目录中,然后访问该目录以上传文件。

当我尝试这样做时,我收到此错误:PermissionError: [Errno 13] Permission denied: 'C:\\Users\\[MyName]\\AppData\\Local\\Temp\\tmpbpom7ull'

这是我正在使用的代码,如果有人有任何其他方式将 FileStorage 对象上传到 Google 存储云或访问已保存文件的方式,将不胜感激!

# File is currently a "FileStorage" object from werkzeug, gotten by doing
# file = request.files["filename"]
tempdir = tempfile.mkdtemp()
file.name = filename
file.save(tempdir)

upload_blob(BUCKET_NAME,filename,filename)

【问题讨论】:

    标签: python file flask google-cloud-platform temporary-files


    【解决方案1】:

    跟进昨天的Flask: Could not authenticate question the Google Cloud Storage client,你可以按照Flask-GoogleStorageusage中的描述使用werkzeug的FileStorage对象:

    假设您在工作目录中有一个文件hellofreddie.txt

    hellofreddie.txt:

    Hello Freddie!
    

    然后您可以open 它,创建一个FileStorage 对象,然后在Bucket 对象(files)上使用save

    from datetime import timedelta
    
    from flask import Flask
    from flask_googlestorage import GoogleStorage, Bucket
    from werkzeug.datastructures import FileStorage
    
    import os
    
    
    files = Bucket("files")
    storage = GoogleStorage(files)
    
    app = Flask(__name__)
    app.config.update(
        GOOGLE_STORAGE_LOCAL_DEST = app.instance_path,
        GOOGLE_STORAGE_SIGNATURE = {"expiration": timedelta(minutes=5)},
        GOOGLE_STORAGE_FILES_BUCKET = os.getenv("BUCKET")
    )
    storage.init_app(app)
    
    with app.app_context():
        with open("hellofreddie.txt","rb") as f:
            file = FileStorage(f)
            filename = files.save(file)
    

    代码运行后,您将看到在 Cloud Storage 中创建了一个以 UUID 命名的等效项。

    您可以使用存储浏览器或gsutil:

    gsutil ls gs://${BUCKET}
    gs://{BUCKET}/361ea9ea-5599-4ff2-84d1-3fe1a802ac08.txt
    

    注意尝试print files.url(filename)files.signed_url(filename) 时,我无法解决问题。这些方法正确返回云存储对象,但返回 PurePosixPath('f3745268-5c95-4c61-a892-09c0de556635.txt')。我的 Python 天真。

    【讨论】:

      【解决方案2】:

      我已经意识到我的错误,我试图将 file.save() 用于文件夹而不是实际文件,我的代码已更新为

      tempdir = tempfile.mkdtemp()
          file.name = filename
          file.save(tempdir + "/" + filename)
      
          upload_blob(BUCKET_NAME,tempdir + "/" + filename,filename)
      

      感谢PermissionError: [Errno 13] Permission denied

      【讨论】:

        猜你喜欢
        • 2021-11-05
        • 2018-10-31
        • 1970-01-01
        • 2017-04-02
        • 2019-11-07
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多