我正在构建一个应用引擎端点api,从用户(android应用程序)拍照,并以编程方式将其保存到blobstore。然后将blob_key保存在数据存储中。代码是这样的:
-
首先,我通过
@endpoint.method
接收图像作为messages.BytesField
:image_data = messages。BytesField (1 = True)
然后像这样保存到blobstore:
from google.appengine.api import files
def save_image(data):
# Create the file
file_name = files.blobstore.create(mime_type='image/png')
# Open the file and write to it
with files.open(file_name, 'a') as f:
f.write('data')
# Finalize the file. Do this before attempting to read it.
files.finalize(file_name)
# Get the file's blob key
blob_key = files.blobstore.get_blob_key(file_name)
return blob_key # which is then saved to datastore
现在我想返回图像。我不知道如何将以下代码放入我的端点api中:
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, resource):
resource = str(urllib.unquote(resource))
blob_info = blobstore.BlobInfo.get(resource)
self.send_blob(blob_info)
最后我设想了一个这样的上菜程序:
- 在@endpoints.method:
get blob_key from datastore
使用blob_key获取图像
add image to StuffResponseMessage
发送StuffResponseMessage到前端(android应用)
我的方法是因为我想保护我的用户的隐私。关于如何做好这件事,有什么想法吗?我的代码片段通常来自google开发者教程。
编辑:
我不知道如何将数据存储中的blob_key传递给以下方法来检索图像:
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, resource):
resource = str(urllib.unquote(resource))
blob_info = blobstore.BlobInfo.get(resource)
self.send_blob(blob_info)
resource
里面到底是什么?
我相信resource
是您想要服务的BlobKey
对象,作为字符串,从url路径检索。如果你看一下google.appengine.ext.blobstore.BlobInfo
的源代码,get
方法使用了一个函数__normalize_and_convert_keys
,它接受BlobKey
对象或字符串的参数。
如果blob是图像,也许最好将服务url发送到您的Android应用程序,在StuffResponseMessage
中可能在您的情况下。摘自google的服务Blob文档:
如果你正在提供图像,一个更有效和可能更便宜的方法是使用get_serving_url使用应用引擎图像API,而不是send_blob。get_serving_url函数可以让你直接提供图像,而不必经过App Engine实例。
所以在你保存图像之后,采取返回的blob_key
(按照上面的方法save_image(data)
)来制作一个服务url,然后在你的Android应用程序中从返回的url中获取图像。这当然意味着在没有隐私保护的情况下暴露图像url。
如果你想做的保护,使用BlobReader
类读取blob与文件一样的接口。您不能使用服务Blob示例中的方法/类,因为您是在remote.Service
子类而不是处理程序中进行的。