Almacenar imágenes en google almacén de datos utilizando el frasco (Python)
-
26-09-2019 - |
Pregunta
Estoy utilizando el frasco de Google App Engine y estoy buscando desesperadamente ayuda para resolver esto. Las conversaciones de documentación GAE de almacenamiento de imágenes en el almacén de datos utilizando el BlobProperty, lo que se debe hacer algo como esto: -
class MyPics(db.Model):
name=db.StringProperty()
pic=db.BlobProperty()
Ahora la imagen se debe almacenar en el almacén de datos al hacer esto: -
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
Pero soy incapaz de hacerlo. como consigo db.Blob acepta una cadena, pero dado un objeto Filestorage ... ¿Puede alguien ayudarme con esto. También si alguien me podría hacer alusión sobre la forma de transmitir la parte de atrás de imagen después de la carga.
Solución
La autorización así que así es como finalmente lo solucioné: -
@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')
Las tiendas anteriores el archivo como una gota en el almacén de datos y luego se puede recuperar mediante el siguiente func: -
@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)
Otros consejos
Se debe considerar el uso de la BlobStore
para almacenar sus datos. En lugar de un db.Blob
que estaría utilizando blobstore.BlobReferenceProperty
: http: // código .google.com / appengine / docs / python / almacén de datos / typesandpropertyclasses.html # BlobReferenceProperty
La carga y descarga es muy fácil, como se muestra aquí: http: //code.google.com/appengine/docs/python/blobstore/overview.html#Complete_Sample_App
He siguiente modelo
class Picture(db.Model):
data = db.BlobProperty()
ext = db.StringProperty()
content_type = db.StringProperty()
y almacenarla utilizar en el siguiente código:
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')
para mostrar una imagen en miniatura se puede utilizar código siguiente:
@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