clifgray
clifgray

Reputation: 4419

Tie a Blob to a Datastore entity

I have been banging my head against the wall on this one, for some reason I am having trouble tying the different aspects of Google App Engine together to make this work.

Basically I want to let a user upload a photo to the Blobstore, which I have working in the below code, and then I want to put the BlobKey into a list which will be stored in a database entity. So here is my code to upload the image and where in here can I get the BlobKey so that I can store it?

class MainHandler(BlogHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        self.response.out.write('<html><body>')
        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""")
        #there is a lot more code in here where I get all the following info but it isn't relevant
        location_db = Location(
                    description=description,
                    submitter=submitter,
                    user_id=user_id, 
                    title=title,
                    locationtype = locationtype)
            #This is what I would like to do but I don't know where to get thr BlobKey
            location_db.blobRefs.append(BlobKey)
            location_db.put()

        for b in blobstore.BlobInfo.all():
            self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>')

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        self.redirect('/main')

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, blob_key):
        blob_key = str(urllib.unquote(blob_key))
        if not blobstore.get(blob_key):
            self.error(404)
        else:
            self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)

Upvotes: 0

Views: 289

Answers (1)

Paul Collingwood
Paul Collingwood

Reputation: 9116

Here:

blob_info = upload_files[0]
self.redirect('/serve/%s' % blob_info.key())

I think it's that

blob_info.key()

you are missing. Grab that, stuff it into your list. Docs also note:

In this handler, you can store the blob key with the rest of your application's data model. The blob key itself remains accessible from the blob info entity in the datastore. https://developers.google.com/appengine/docs/python/blobstore/overview#Serving_a_Blob

Upvotes: 3

Related Questions