Python 2.7 はサポートが終了しており、2026 年 1 月 31 日に
非推奨になります。非推奨になると、過去に組織のポリシーを使用して以前のランタイムのデプロイを再度有効にしていた場合でも、Python 2.7 アプリケーションをデプロイできなくなります。既存の Python 2.7 アプリケーションは、
非推奨日以降も引き続き実行され、トラフィックを受信します。
サポートされている最新バージョンの Python に移行することをおすすめします。
webapp Blobstore ハンドラ
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
webapp には、Blobstore API で使用するためのリクエスト ハンドラ クラスが含まれます。BlobstoreUploadHandler
は、Blobstore 経由で BlobInfo レコードに渡されるアップロード リクエストを、以降の処理のために解析するロジックを提供します。BlobstoreDownloadHandler
を使用すると、どのパスからでも簡単に Blobstore 値を指定できます。
BlobstoreUploadHandler
Blobstore には、アプリケーションのユーザーまたは管理者によるファイル アップロードを介して値が追加されます。アプリケーションは、ファイル アップロード フィールドと、Blobstore へのアップロードを指示するフォーム アクションを含む、ウェブフォームを送信します。アプリは、関数(create_upload_url())を呼び出し、ユーザーがファイルをアップロードしたときに呼び出されるアプリハンドラの URL をその関数に渡すことにより、フォーム アクションの URL を取得します。webapp アプリケーションは、この URL のハンドラとして BlobstoreUploadHandler
クラスのサブクラスを使用できます。
get_uploads()
メソッドは、リクエストに含まれるアップロードされたファイルごとに 1 つずつ、BlobInfo オブジェクトのリストを返します。各オブジェクトには、アップロードした値の Blobstore キーの他、ファイル名やサイズなどのメタデータが含まれます。アップロードした各ファイルについては、この情報が含まれる対応するエンティティがデータストア内にもあるため、後で blob キーを指定して BlobInfo オブジェクトを取得したり、メタデータのフィールドでデータストア クエリを実行したりすることができます。アップロード ハンドラは、この情報をデータストアではなく要求データから直接解析します。
デフォルトでは、get_uploads()
は、リクエストでアップロードしたすべてのファイルについて BlobInfo オブジェクトを返します。また、このメソッドは field_name
引数を受け取って、特定のファイル アップロード フィールドのファイルのみを取得することもします。戻り値は常にリストで、空のリストの場合もあります。
Google Cloud Storage での BlobstoreUploadHandler
の使用
Cloud Storage でこのアップロード ハンドラを使用する場合は、完全な Cloud Storage オブジェクト ファイル名を取得して保存する必要があります。これは、Cloud Storage からファイルを再度取得する際に必要となるためです。関数 get_file_infos
を使用します。この関数は、それぞれのアップロードに対応する FileInfo レコードのリストを返します。完全な Cloud Storage オブジェクト名、コンテンツ タイプ、作成日時などのデータを FileInfo
から取得できます(詳細についてはリンク先をご覧ください)。
BlobstoreDownloadHandler
Blobstore 値を提供するために、アプリケーションは X-AppEngine-BlobKey
ヘッダーを文字列形式で Blobstore キーの値に設定します。App Engine では、応答でこのヘッダーを認識すると、応答の本文として blob の値を提供します。webapp ハンドラクラス BlobstoreDownloadHandler
により、応答にこの値を簡単に設定できます。
send_blob()
メソッドは、BlobKey オブジェクト、文字列キー、または BlobInfo を blob_key_or_info
引数として受け取り、blob 値がユーザーに提供されるように応答データを設定します。このメソッドは、保存された blob 値の MIME コンテンツ タイプを上書きする、オプションの content_type
引数を受け取ります。デフォルトで blob は、アップロードしたクライアントによって設定されたコンテンツ タイプ、ファイル名から派生したコンテンツ タイプ、一般的なタイプ(他のタイプ情報が利用できない場合)のいずれかのコンテンツ タイプで提供されます。
send_blob()
メソッドは save_as
引数を受け入れます。この引数は、blob データが生の応答データとして送信されるか、ファイル名を持つ MIME 添付ファイルとして送信されるかを決定します。引数が文字列の場合、blob は添付ファイルとして送信され、文字列値がファイル名として使用されます。True
と blob_key_or_info
が BlobInfo
オブジェクトである場合は、このオブジェクトのファイル名が使用されます。デフォルトでは、blob データは MIME 添付ファイルではなく、応答の本文として送信されます。
Blobstore では、バイト インデックスの範囲として記述することにより、値全体ではなく値の一部のみを送信できます。バイト インデックスの範囲を BlobstoreDownloadHandler
の send_blob()
メソッドに指定する方法は 2 つあります。1 つ目の方法は、引数 start
と引数 end
として範囲を指定することです。
# Send the first 1,000 bytes of the value.
self.send_blob(key, start=0, end=999)
デフォルトでは、BlobstoreDownloadHandler
はリクエストの range
ヘッダーを使用します。元の範囲のヘッダーが使用されないようにするには、パラメータ use_range=False
を send_blob()
に指定します。
# Send the full value of the blob and
# block the "range" header.
self.send_blob(key, use_range=False)
range
ヘッダーの値は、標準の HTTP バイト範囲です。BlobstoreDownloadHandler
は webob.byterange を使用して、このヘッダー値を解析します。
サンプル アプリケーションを完成させる
以下のサンプル アプリケーションでは、アプリケーションのメイン URL でユーザーにファイルのアップロードを求めるフォームを読み込みます。アップロード ハンドラはすぐにダウンロード ハンドラを呼び出し、データを提供します。これは、サンプル アプリケーションを簡略化するためのものです。実際にはアップロード データのリクエストにメイン URL を使用したり、アップロードした blob をすぐに提供したりしないはずです。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-09-04 UTC。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["わかりにくい","hardToUnderstand","thumb-down"],["情報またはサンプルコードが不正確","incorrectInformationOrSampleCode","thumb-down"],["必要な情報 / サンプルがない","missingTheInformationSamplesINeed","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-09-04 UTC。"],[[["\u003cp\u003e\u003ccode\u003eBlobstoreUploadHandler\u003c/code\u003e is used to manage file uploads to the Blobstore, parsing upload requests and providing \u003ccode\u003eBlobInfo\u003c/code\u003e objects containing data about each file.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eget_uploads()\u003c/code\u003e method retrieves a list of \u003ccode\u003eBlobInfo\u003c/code\u003e objects for uploaded files, offering options to filter by specific file upload fields.\u003c/p\u003e\n"],["\u003cp\u003eWhen using \u003ccode\u003eBlobstoreUploadHandler\u003c/code\u003e with Google Cloud Storage, \u003ccode\u003eget_file_infos\u003c/code\u003e should be used to get a \u003ccode\u003eFileInfo\u003c/code\u003e record, in order to obtain the full cloud storage object name.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eBlobstoreDownloadHandler\u003c/code\u003e facilitates serving Blobstore values by setting the \u003ccode\u003eX-AppEngine-BlobKey\u003c/code\u003e header, allowing you to serve blobs directly to users from a specific path.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003esend_blob()\u003c/code\u003e method in \u003ccode\u003eBlobstoreDownloadHandler\u003c/code\u003e provides options to serve blobs as raw data or as a MIME attachment with a filename, and supports sending partial blob data via byte ranges.\u003c/p\u003e\n"]]],[],null,["# webapp Blobstore Handlers\n\nwebapp includes request handler classes for working with the\n[Blobstore API](/appengine/docs/legacy/standard/python/blobstore). `BlobstoreUploadHandler`\nprovides logic for parsing the upload request passed via the Blobstore into\n[BlobInfo](/appengine/docs/legacy/standard/python/refdocs/google.appengine.ext.blobstore.blobstore#google.appengine.ext.blobstore.blobstore.BlobInfo)\nrecords for further processing. `BlobstoreDownloadHandler` makes it easy to serve\nBlobstore values from any path.\n\nBlobstoreUploadHandler\n----------------------\n\nValues are added to the Blobstore via file uploads posted by users or administrators of the app.\nThe app posts a web form with a file upload field and a form action that directs the upload to the\nBlobstore. The app gets the form action URL by calling a function\n([create_upload_url()](/appengine/docs/legacy/standard/python/refdocs/google.appengine.ext.blobstore.blobstore#google.appengine.ext.blobstore.blobstore.create_upload_url)),\npassing it the URL of an app handler that gets called when users upload files. A webapp\napplication can use a subclass of the `BlobstoreUploadHandler` class as the handler for\nthis URL.\n\nThe `get_uploads()` method returns a list of\n[BlobInfo](/appengine/docs/legacy/standard/python/refdocs/google.appengine.ext.blobstore.blobstore#google.appengine.ext.blobstore.blobstore.BlobInfo)\nobjects, one for each uploaded file in the request. Each object contains the Blobstore key for\nthe uploaded value, as well as metadata such as the filename and size. Each uploaded file also\nhas a corresponding entity in the datastore with this information, so you can fetch the BlobInfo\nobject later given a blob key, or perform a datastore query over the metadata fields. The upload\nhandler parses this information directly from the request data, not the datastore.\n\nBy default, `get_uploads()` returns BlobInfo objects for all uploaded files in the\nrequest. The method also accepts a `field_name` argument to get just the file (or\nfiles) for a given file upload field. The return value is always a list, possibly an empty list. \n\n class PhotoUploadHandler(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n upload = self.get_uploads()[0]\n user_photo = UserPhoto(\n user=users.get_current_user().user_id(),\n blob_key=upload.key())\n user_photo.put()\n\n self.redirect('/view_photo/%s' % upload.key())\n\n### Using `BlobstoreUploadHandler` with Google Cloud Storage\n\nIf you use this upload handler with Cloud Storage, you'll need to get and store the full\nCloud Storage object file name, since this is required to retrieve the file again from Cloud Storage.\nUse the function `get_file_infos`, which returns a list of\n[FileInfo](/appengine/docs/legacy/standard/python/refdocs/google.appengine.ext.blobstore.blobstore#google.appengine.ext.blobstore.blobstore.FileInfo) records\ncorresponding to each upload. The full Cloud Storage object name, content type, creation\ntime, and other data are available in the `FileInfo`. (See the link for complete details.)\n\nBlobstoreDownloadHandler\n------------------------\n\nTo serve a Blobstore value, the application sets the `X-AppEngine-BlobKey` header to\nthe value of a Blobstore key, in string form. When App Engine sees this header in the response,\nit serves the value of the blob as the body of the response. The webapp handler class\n`BlobstoreDownloadHandler` makes it easy to set this value in the response.\n\nThe `send_blob()` method takes a\n[BlobKey](/appengine/docs/legacy/standard/python/refdocs/google.appengine.ext.blobstore.blobstore#google.appengine.ext.blobstore.blobstore.BlobKey)\nobject, a string key, or a\n[BlobInfo](/appengine/docs/legacy/standard/python/refdocs/google.appengine.ext.blobstore.blobstore#google.appengine.ext.blobstore.blobstore.BlobInfo)\nas the `blob_key_or_info` argument, and sets the response data so that the blob value\nwill be served to the user. The method takes an optional `content_type` argument which\noverrides the MIME content type of the stored blob value. By default, the blob is served with the\ncontent type set by the client that uploaded it, a content type derived from the filename, or a\ngeneric type if no other type information is available.\n\nThe `send_blob()` method accepts a `save_as` argument that determines\nwhether the blob data is sent as raw response data or as a MIME attachment with a filename. If\nthe argument is a string, the blob is sent as an attachment, and the string value is used as\nthe filename. If `True` and `blob_key_or_info` is a `BlobInfo`\nobject, the filename from the object is used. By default, the blob data is sent as the body of\nthe response and not as a MIME attachment. \n\n class ViewPhotoHandler(blobstore_handlers.BlobstoreDownloadHandler):\n def get(self, photo_key):\n if not blobstore.get(photo_key):\n self.error(404)\n else:\n self.send_blob(photo_key)\n\nThe Blobstore supports sending just part of a value instead of the full value, described as a range of byte indexes. You can provide a byte index range to `BlobstoreDownloadHandler`'s `send_blob()` method in two ways. The first is to specify the range as the arguments `start` and `end`: \n\n```python\n # Send the first 1,000 bytes of the value.\n self.send_blob(key, start=0, end=999)\n```\n\nBy default, the `BlobstoreDownloadHandler` honors the `range` header in the request. If you wish to block use of the original range header, provide the parameter `use_range=False` to `send_blob()`: \n\n```python\n # Send the full value of the blob and\n # block the \"range\" header.\n self.send_blob(key, use_range=False)\n```\n\nThe value of the `range` header is a standard [HTTP byte range](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). `BlobstoreDownloadHandler` uses [webob.byterange](http://pythonpaste.org/webob/modules/webob.html) to parse this header value.\n\nComplete sample application\n---------------------------\n\nIn the following sample application, the application's main URL loads the form that asks the user\nfor a file to upload, and the upload handler immediately calls the download handler to serve the\ndata. This is to simplify the sample application. In practice, you would probably not use the main\nURL to request upload data, nor would you immediately serve a blob you had just uploaded. \n\n from google.appengine.api import users\n from google.appengine.ext import blobstore\n from google.appengine.ext import ndb\n from google.appengine.ext.webapp import blobstore_handlers\n import webapp2\n\n\n # This datastore model keeps track of which users uploaded which photos.\n class UserPhoto(ndb.Model):\n user = ndb.StringProperty()\n blob_key = ndb.BlobKeyProperty()\n\n\n class PhotoUploadFormHandler(webapp2.RequestHandler):\n def get(self):\n upload_url = blobstore.create_upload_url('/upload_photo')\n # To upload files to the blobstore, the request method must be \"POST\"\n # and enctype must be set to \"multipart/form-data\".\n self.response.out.write(\"\"\"\n \u003chtml\u003e\u003cbody\u003e\n \u003cform action=\"{0}\" method=\"POST\" enctype=\"multipart/form-data\"\u003e\n Upload File: \u003cinput type=\"file\" name=\"file\"\u003e\u003cbr\u003e\n \u003cinput type=\"submit\" name=\"submit\" value=\"Submit\"\u003e\n \u003c/form\u003e\n \u003c/body\u003e\u003c/html\u003e\"\"\".format(upload_url))\n\n\n class PhotoUploadHandler(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n upload = self.get_uploads()[0]\n user_photo = UserPhoto(\n user=users.get_current_user().user_id(),\n blob_key=upload.key())\n user_photo.put()\n\n self.redirect('/view_photo/%s' % upload.key())\n\n\n class ViewPhotoHandler(blobstore_handlers.BlobstoreDownloadHandler):\n def get(self, photo_key):\n if not blobstore.get(photo_key):\n self.error(404)\n else:\n self.send_blob(photo_key)\n\n\n app = webapp2.WSGIApplication([\n ('/', PhotoUploadFormHandler),\n ('/upload_photo', PhotoUploadHandler),\n ('/view_photo/([^/]+)?', ViewPhotoHandler),\n ], debug=True)"]]