在Flask(Python)中使用Google Datastore存储图像
我在谷歌应用引擎上使用flask,现在非常需要帮助来解决这个问题。GAE的文档提到可以使用BlobProperty将图片存储在数据存储中,应该像这样做:
class MyPics(db.Model):
name=db.StringProperty()
pic=db.BlobProperty()
现在,应该通过这样的方法将图片存储到数据存储中:
def storeimage():
pics=MyPics()
pics.name=request.form['name']
uploadedpic=request.files['file'] #where file is the fieldname in the form of the
file uploaded
pics.pic=db.Blob(uploadedpic)
pics.put()
redirect ... etc etc
但是我做不到,因为我收到的错误是db.Blob接受一个字符串,但我给的是一个Filestorage对象……有人能帮我解决这个问题吗?另外,如果有人能告诉我上传后如何将图片流回去,那就太好了。
3 个回答
0
我有以下这个模型
class Picture(db.Model):
data = db.BlobProperty()
ext = db.StringProperty()
content_type = db.StringProperty()
并且使用下面的代码来存储它:
def create_picture():
if request.files['file']:
picture.data = request.files['file'].read()
picture.ext = request.files['file'].filename.rsplit('.', 1)[1]
picture.content_type = request.files['file'].content_type
picture.put()
flash(u'File uploaded', 'correct')
return redirect(url_for("edit_picture", id=picture.key()))
else:
return render_template('admin/pictures/new.html', title=u'Upload a picture', message=u'No picture selected')
要显示一个缩略图,你可以使用下面的代码:
@frontend.route('/thumbnail/<id>/<width>x<height>.<ext>')
def thumbnail(id, width, height, ext):
key = db.Key(id)
picture = Picture.get(key)
img = images.Image(picture.data)
if width != '0':
w = int(width)
else:
w = img.width
if height != '0':
h = int(height)
else:
h = img.height
if img.height > h and h != 0:
w = (int(width) * img.width) / img.height;
if img.width > w:
h = (int(height) * img.height) / img.width;
thumb = images.resize(picture.data, width=w, height=h)
response = make_response(thumb)
response.headers['Content-Type'] = picture.content_type
return response
1
你可以考虑使用 BlobStore
来存储你的数据。与其使用 db.Blob
,不如用 blobstore.BlobReferenceProperty
,具体可以参考这个链接:http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#BlobReferenceProperty
上传和下载数据其实很简单,具体的操作可以参考这里的示例:http://code.google.com/appengine/docs/python/blobstore/overview.html#Complete_Sample_App
6
好的,这就是我最终解决问题的方法:
@userreg.route('/mypics',methods=['GET','POST'])
def mypics():
if request.method=='POST':
mydata=MyPics()
mydata.name=request.form['myname']
file=request.files['file']
filedata=file.read()
if file:
mydata.pic=db.Blob(filedata)
mydata.put()
return redirect(url_for('home'))
return render_template('mypicform.html')
上面的代码把文件存储为一个“二进制大对象”(blob)在数据存储中,然后可以通过下面的函数来取回这个文件:
@userreg.route('/pic/<name>')
def getpic(name):
qu=db.Query(MyPics).filter('name =',name).get()
if qu.pic is None:
return "hello"
else:
mimetype = 'image/png'
return current_app.response_class(qu.pic,mimetype=mimetype,direct_passthrough=False)