我在尝试创建一个可以从GAE数据存储中提供图像的脚本时收到此错误。
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/datastore_types.py", line 379, in __init__
raise datastore_errors.BadKeyError('Invalid string key %s.' % encoded)
BadKeyError: Invalid string key 5066549580791808.
使用此代码:
class ImageHandler(MainHandler):
def get(self):
greeting = db.get(self.request.get('id'))
if greeting.image:
self.response.headers['Content-Type'] = 'image/png'
self.response.out.write(greeting.image)
else:
self.error(404)
此课程是根据GAE上的image documentation
创建的答案 0 :(得分:4)
5066549580791808不是密钥,它是一个id。
您需要使用SomeModel.get()
,db.get()
需要整个密钥,其中包括模型和路径。
答案 1 :(得分:2)
另一种选择是使用Blobstore API
通过这种方式,您可以使用图片API即时提供不同尺寸的图片:Transforming images from the Blobstore
import webapp2
from google.appengine.api import images
from google.appengine.ext import blobstore
class Thumbnailer(webapp2.RequestHandler):
def get(self):
blob_key = self.request.get("blob_key")
if blob_key:
blob_info = blobstore.get(blob_key)
if blob_info:
img = images.Image(blob_key=blob_key)
img.resize(width=80, height=100)
img.im_feeling_lucky()
thumbnail = img.execute_transforms(output_encoding=images.JPEG)
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(thumbnail)
return
# Either "blob_key" wasn't provided, or there was no value with that ID
# in the Blobstore.
self.error(404)