本頁面說明如何搭配使用 Blobstore API (舊版套裝服務之一) 和 Python 3 執行階段,以標準環境為例。您的應用程式可以透過 Python 3 專用的 App Engine 服務 SDK存取套裝組合服務。
總覽
由於 Python 3 不支援 webapp,因此您需要在將 Blobstore 處理常式程式碼從 Python 2 遷移至 Python 3 時,進行一些必要的變更。如要使用 Python 3 的 Blobstore API,請注意下列事項:
Blobstore 處理常式類別是公用程式類別。這表示處理常式類別不再以 webapp 為基礎,您無法使用 webapp 套件 (
google.appengine.ext.webapp
) 提供的blobstore_handlers
模組,或這些處理常式子類別中的webapp2.RequestHandler
參數。Blobstore 處理常式類別中的所有方法都需要 WSGI
environ
字典做為輸入參數。
以下各節說明如何在 Flask 應用程式和不使用 Python 架構的 WSGI 應用程式中,使用 Python 3 的 BlobstoreUploadHandler
和 BlobstoreDownloadHandler
類別。您可以將 Python 3 範例與 Python 2 範例程式碼進行比較,進一步瞭解程式碼變更的差異。
範例:Flask 應用程式
在 Python 3 中,Blobstore 處理常式類別屬於 google.appengine.ext.blobstore
模組的一部分。對於 Flask 應用程式,所有對 BlobstoreUploadHandler
和 BlobstoreDownloadHandler
類別中方法的呼叫都需要 request.environ
字典 (request
會從 flask
模組匯入)。
比較從 Python 2 (webapp2) 到 Python 3 (Flask) 的程式碼變更。請注意,Flask 應用程式如何在 get_uploads()
和 send_blob()
方法中使用 request.environ
參數:
Python 2 (webapp2)
class PhotoUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
user_photo = UserPhoto(
user=users.get_current_user().user_id(),
blob_key=upload.key())
user_photo.put()
self.redirect('/view_photo/%s' % upload.key())
class ViewPhotoHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, photo_key):
if not blobstore.get(photo_key):
self.error(404)
else:
self.send_blob(photo_key)
app = webapp2.WSGIApplication([
('/', PhotoUploadFormHandler),
('/upload_photo', PhotoUploadHandler),
('/view_photo/([^/]+)?', ViewPhotoHandler),
], debug=True)
Python 3 (Flask)
如要查看 Python 3 (Flask) 的完整程式碼範例,請參閱 GitHub。
範例:不含網路架構的 WSGI 應用程式
以下 Python 3 (WSGI 應用程式) 程式碼示範如何在沒有網頁架構的情況下,為 WSGI 應用程式使用 Blobstore 處理常式類別,並新增 environ
參數。請注意 get_uploads()
和 send_blob()
方法如何使用 environ
參數,並與 Python 2 版本進行比較:
Python 2
class PhotoUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
user_photo = UserPhoto(
user=users.get_current_user().user_id(),
blob_key=upload.key())
user_photo.put()
self.redirect('/view_photo/%s' % upload.key())
class ViewPhotoHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, photo_key):
if not blobstore.get(photo_key):
self.error(404)
else:
self.send_blob(photo_key)
app = webapp2.WSGIApplication([
('/', PhotoUploadFormHandler),
('/upload_photo', PhotoUploadHandler),
('/view_photo/([^/]+)?', ViewPhotoHandler),
], debug=True)
Python 3
如要查看 Python 3 的完整程式碼範例,請前往 GitHub。