Uploading a video to google app engine blobstore

旧街凉风 提交于 2019-12-03 21:09:44

Here's the code I'm using to upload images and associate them with articles. The toughest bit was getting the article id to get to the upload handler, I solved it by setting the file name as the article id to get around the problem.

from lib import urllib2_file
from lib.urllib2_file import UploadFile

# this view serves a task in a queue
def article(request):
       article = Article.objects.get(id=form.cleaned_data['article'])

       try:
            image = StringIO(urllib2.urlopen(image_url).read())
        except (urllib2.HTTPError, DownloadError):
            article.parsed = True
            article.save()
        else:
            image = UploadFile(image, '.'.join([str(article.id), image_url.rsplit('.', 1)[1][:4]]))
            upload_url = blobstore.create_upload_url(reverse('Articles.views.upload'))

            try:
                urllib2.urlopen(upload_url, {'file': image})
            except (DownloadError, RequestTooLargeError):
                pass

    return HttpResponse(json.dumps({'status': 'OK'}))

def upload(request):
    if request.method == 'POST':
        blobs = get_uploads(request, field_name='file', populate_post=True)

        article = Article.objects.get(id=int(blobs[0].filename.split('.')[0]))
        article.media = blobs[0].filename
        article.parsed = True
        article.save()

        return HttpResponseRedirect(reverse('Articles.views.upload'))
    else:
        return HttpResponse('meow')

    def upload(request):
        if request.method == 'POST':
            blobs = get_uploads(request, field_name='file', populate_post=True)

            article = Article.objects.get(id=int(blobs[0].filename.split('.')[0]))
            article.media = blobs[0].filename
            article.parsed = True
            article.save()

            return HttpResponseRedirect(reverse('Articles.views.upload'))
        else:
            return HttpResponse('meow')

# this serves the image
def image(request):
    blob = BlobInfo.gql("WHERE filename='%s' LIMIT 1" % request.form.cleaned_data['id'])[0]

    return HttpResponse(BlobReader(blob.key()).read(),
                        content_type=blob.content_type)

Also you'll need this http://fabien.seisen.org/python/urllib2_file/

Here is how I did it. It is more straight forward than you think. Note the following taken from Blobstore overview. "When the Blobstore rewrites the user's request, the MIME parts of the uploaded files have their bodies emptied, and the blob key is added as a MIME part header. All other form fields and parts are preserved and passed to the upload handler." In the upload handler is where you can do whatever it is you want with the other form fields.

    class Topic(db.Model):
        title = db.StringProperty(multiline=False)
        blob = blobstore.BlobReferenceProperty()
        imageurl = db.LinkProperty()

    class MainHandler(webapp.RequestHandler):
        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>
            <div><label>Title:</label></div>
            <div><textarea name="title" rows="1" cols="25"></textarea></div><input type="submit" 
                name="submit" value="Submit"> </form>""")
            self.response.out.write('<br><br><h2>TOPIC LIST</h2><table border="1"><tr><td>')
            for topic in Topic.all():                
                self.response.out.write('<div><img src="%s=s48"/>' % topic.imageurl)
                self.response.out.write('<div><b>Image URL: </b><i>%s</i></div>' % topic.imageurl)
                self.response.out.write('<div><b>Title: </b><i>%s</i></div>' % topic.title)
            self.response.out.write('</td></tr></table><br>') 
            self.response.out.write('</body></html>')

    class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
        def post(self):
            upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
            blob_info = upload_files[0]
            topic = Topic()
            topic.title = self.request.get("title")
            topic.blob = blob_info.key()
            topic.imageurl = images.get_serving_url(str(blob_info.key()))
            topic.put()        
            self.redirect('/')
def main():
    application = webapp.WSGIApplication(
          [('/', MainHandler),
           ('/upload', UploadHandler),
          ], debug=True)
    run_wsgi_app(application)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!