![](/img/trans.png)
[英]Trying to verify SHA1 message signature using Python. What am I doing wrong?
[英]I'm unable to upload a file whose name has a space in it to Google Cloud Storage using Python. What am I doing wrong?
我是 Python 和 Google Cloud 的新手。 使用 Flask 我創建了一個 web 頁面,用戶可以在其中從他們的計算機中選擇一個文件並將其上傳到我已經創建的 GCS 存儲桶中。 我正在關注使用 Google Python API 庫的 Google 文檔示例。 我可以上傳名稱只有一個單詞的文件,例如“image”,但如果我的文件名為“image one”,則會出現以下錯誤- FileNotFoundError: [Errno 2] No such file or directory: 'image一個.jpg'
這是我的代碼:
@app.route('/upload', methods = ['GET' , 'POST'])
def upload():
if request.method == "POST":
f = request.files['file']
f.save(secure_filename(f.filename))
gcs_upload(f.filename)
def gcs_upload(filename):
storage_client = storage.Client() # instantiate a client
bucket = storage_client.bucket('bucket_name')
blob=bucket.blob(filename) # file name at the destination should be the same
blob.upload_from_filename(filename) # file to be uploaded
if __name__ == '__main__':
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
app.run(port=8080, debug=True)
如果我正在編寫一個生產級應用程序,那么我希望用戶上傳一個文件,即使它的名稱中有空格。
我在我自己的項目中重現了這個問題,你面臨的問題是由於使用了secure_filename function。 根據werkzeug 文檔,function secure_filename 將用下划線替換用戶提供的文件名的任何空格。 添加一些日志記錄,您可能會看到:
f.filename # 'foo bar.png'
secure_filename(f.filename) # 'foo_bar.png'
因此,當您調用gcs_upload function 時,您傳遞的是原始文件名,而不是 secure_filename 返回的文件名,並且錯誤消息指出該文件不存在。
要解決此問題,只需將上傳 function 更改為:
def upload():
if request.method == "POST":
f = request.files['file']
filename = secure_filename(f.filename)
f.save(filename)
gcs_upload(filename)
嘗試在之前引用文件名(通過使用urllib )。 這是一個使用python3的示例:
import urllib.parse
filename = "files name.jpg"
new_file = str(urllib.parse.quote(filename))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.