[英]Upload Files To Google Cloud Storage With Google App Engine (Python)
[英]Python App Engine serving files with Google Cloud Storage
我目前使用以下代碼允許我的用戶上傳文件;
uploadurl = blobstore.create_upload_url('/process?session=' + session, gs_bucket_name='mybucketname')
我可以提供這樣的圖像;
imgurl = get_serving_url(blob_key, size=1600, crop=False, secure_url=True)
使用第一個代碼片段中的方法上傳內容后,blob密鑰包含encoded_gs_file:
這就是它知道如何從Google Cloud Service而不是blobstore提供服務的標准方式。
但是,我不確定如何提供其他任何類型的文件(例如.pdf或.rtf)。 我不希望將內容顯示在瀏覽器中,而是將其作為下載內容發送給客戶端(因此,他們會看到“保存文件”對話框,並在計算機上選擇一個位置進行保存)。
我將如何去做呢? 謝謝。
使用google serve_url僅適用於圖像。
要從Blobstore提供pdf,可以使用:
class DynServe(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, resource):
(blob_key, extension) = resource.rpartition('.')[::2]
blob_info = blobstore.BlobInfo.get(blob_key)
if not blob_info:
logging.error('Blob NOT FOUND %s' % resource)
self.abort(404)
self.response.headers[b'Content-Type'] = mimetypes.guess_type(blob_info.filename)
self.send_blob(blob_key, save_as=blob_info.filename)
此處理程序的webapp2路由如下所示:
webapp2.Route(r'/dynserve/<resource:(.*)>', handler=DynServe)
服務:
<a href="/dynserve/<blob_key>.pdf">PDF download</a>
我要根據@voscausa的回答來回答自己的問題
這就是我的處理程序的樣子(在名為view.py
的文件中);
class DynServe(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, resource):
blob_key = resource
if not blobstore.get(blob_key):
logging.warning('Blob NOT FOUND %s' % resource)
self.abort(404)
return
else:
blob_info = blobstore.BlobInfo.get(blob_key)
self.send_blob(blob_key, save_as=blob_info.filename)
我們在app.yaml
需要它;
- url: /download/.*
script: view.app
secure: always
secure: always
是可選的,但是我在處理用戶數據時總是使用它。
把它放在view.py
的底部;
app = webapp.WSGIApplication([('/download/([^/]+)?', DynServe),
], debug=False)
現在訪問/ download / BLOB_KEY_HERE。 (您可以檢查數據存儲區中的Blob鍵)
這是一個完全正常的示例,可與標准Blob存儲和Google Cloud Service一起使用。
注意:屬於GCS的所有Blob密鑰都將以encoded_gs_file:
開頭encoded_gs_file:
那些不在標准Blobstore中; app引擎會自動使用它來確定文件的位置
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.