2013-08-22 70 views
0

我在GAE/Python上使用Flask Web Framework。將文件上傳到雲存儲後,我想獲得對該文件的引用,以便它可以被提供。我無法使parse_file_info正常工作。我花了很長時間努力搜索,花了兩天時間來完成這項工作。我在我的智慧結束!您可以在下面看到我的處理程序:GAE +雲存儲 - 文件上傳後無法獲取FileInfo

@app.route('/upload_form', methods = ['GET']) 
def upload_form(): 
    blobupload_url = blobstore.create_upload_url('/upload', gs_bucket_name = 'mystorage')   
    return render_template('upload_form.html', blobupload_url = blobupload_url)  

@app.route('/upload', methods = ['POST']) 
def blobupload():  
    file_info = blobstore.parse_file_info(cgi.FieldStorage()['file']) 
    return file_info.gs_object_name 

回答

1

數據在您上傳blob後檢索的uploaded_file的有效負載中編碼。這是如何提取名稱的示例代碼:

import email 
from google.appengine.api.blobstore import blobstore 

def extract_cloud_storage_meta_data(file_storage): 
    """ Exctract the cloud storage meta data from a file. """ 
    uploaded_headers = _format_email_headers(file_storage.read()) 
    storage_object_url = uploaded_headers.get(blobstore.CLOUD_STORAGE_OBJECT_HEADER, None) 
    return tuple(_split_storage_url(storage_object_url)) 

def _format_email_headers(raw_headers): 
    """ Returns an email message containing the headers from the raw_headers. """ 
    message = email.message.Message() 
    message.set_payload(raw_headers) 
    payload = message.get_payload(decode=True) 
    return email.message_from_string(payload) 

def _split_storage_url(storage_object_url): 
    """ Returns a list containing the bucket id and the object id. """ 
    return storage_object_url.split("/")[2:4] 

@app.route('/upload', methods = ['POST']) 
def blobupload():  
    uploaded_file = request.files['file'] 
    storage_meta_data = extract_cloud_storage_meta_data(uploaded_file) 
    bucket_name, object_name = storage_meta_data 
    return object_name 
+1

嘿尼克,非常感謝這!但是,您爲什麼不能使用[fileInfo類](https://developers.google.com/appengine/docs/python/blobstore/fileinfoclass?hl=en)? – jess

+0

parse_file_info分析來自cgi.FieldStorage的數據。 Flask只提供一個FileStorage,並且更容易檢索信息,而不是創建具有所有必要屬性的FieldStorage。 –

相關問題