Jan Konarzewski
Jan Konarzewski

Reputation: 21

Google App Engine, uploading videos, python

I am writing an app that lets users upload videos to my site, so i can edit them and sent back to them. I am using google app engine and python. I have read about blobs and stuff but i think is still need a little bit of further explanation.

How it exactly works?

I have written some code using the google blob example code so it seems like files are uploading. However, I dont know how to access them. I dont even know where they are saved.

here is my form

<form method="POST" action="%s" enctype="multipart/form-data">
    Upload file: <input type="file" name="file" /><br />
    </br>
    <input type="submit" name="Submit" value="Submit"/>
  </form>

and here are my handlers:

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.2')

import os
import logging
import cgi
import datetime
import urllib
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from util.sessions import Session
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

# A Model for a User
class User(db.Model):
  account = db.StringProperty()
  password = db.StringProperty()
  name = db.StringProperty()

# A helper to do the rendering and to add the necessary
# variables for the _base.htm template
def doRender(handler, tname = 'index.html', values = { }):
  logging.info('doRender(' + tname + ')')
  temp = os.path.join(
      os.path.dirname(__file__),
      'templates/' + tname)
  logging.info(temp)
  if not os.path.isfile(temp):
    return False

  # Make a copy of the dictionary and add the path and session
  newval = dict(values)
  newval['path'] = handler.request.path
  handler.session = Session()
  if 'username' in handler.session:
     newval['username'] = handler.session['username']
  logging.info(newval)
  outstr = template.render(temp, newval)
  handler.response.out.write(outstr)
  return True


class LoginHandler(webapp.RequestHandler):

  def get(self):
    doRender(self, 'login.html')

  def post(self):
    self.session = Session()
    acct = self.request.get('account')
    pw = self.request.get('password')
    logging.info('Checking account='+acct+' pw='+pw)

    self.session.delete_item('username')
    self.session.delete_item('userkey')

    if pw == '' or acct == '':
      doRender(
          self,
          'login.html',
          {'error' : 'Please specify Account and Password'} )
      return

    que = db.Query(User)
    que = que.filter('account =',acct)
    que = que.filter('password = ',pw)

    results = que.fetch(limit=1)

    if len(results) > 0 :
      user = results[0]
      self.session['userkey'] = user.key()
      self.session['username'] = acct
      doRender(self,'index.html',{ } )
    else:
      doRender(
          self,
          'login.html',
          {'error' : 'Incorrect password'} )

class AddUserHandler(webapp.RequestHandler):

  def get(self):
    doRender(self, 'adduser.html')

  def post(self):
    self.session = Session()
    name = self.request.get('name')
    acct = self.request.get('account')
    pw = self.request.get('password')
    logging.info('Adding account='+acct)

    if pw == '' or acct == '' or name == '':
      doRender(
          self,
          'adduser.html',
          {'error' : 'Please fill in all fields'} )
      return

    # Check if the user already exists
    que = db.Query(User).filter('account =',acct)
    results = que.fetch(limit=1)

    if len(results) > 0 :
      doRender(
          self,
          'adduser.html',
          {'error' : 'Account Already Exists'} )
      return

    # Create the User object and log the user in
    newuser = User(name=name, account=acct, password=pw);
    pkey = newuser.put();
    self.session['username'] = acct
    self.session['userkey'] = pkey
    doRender(self,'index.html',{ })

class LogoutHandler(webapp.RequestHandler):

  def get(self):
    self.session = Session()
    self.session.delete_item('username')
    self.session.delete_item('userkey')
    doRender(self, 'index.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]
        self.redirect('/serve/%s' % blob_info.key())

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)
        self.send_blob(blob_info)

class MainHandler(webapp.RequestHandler):        

  def get(self):
    if doRender(self,self.request.path) :
      return
    doRender(self,'index.html')

def main():
  application = webapp.WSGIApplication([
     ('/login', LoginHandler),
     ('/add-user', AddUserHandler),
     ('/logout', LogoutHandler),
     ('/upload', UploadHandler),
     ('/serve/([^/]+)?',ServeHandler),
     ('/.*', MainHandler)],
     debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()

Can someone help me figure this out? Also, is there any option to save this files directly on my google drive or dropbox?

Thanks for help

Upvotes: 0

Views: 845

Answers (1)

proppy
proppy

Reputation: 10504

You can access blobstore file data using the BlobReader class which behave like a Python file object.

For example:

upload_files = self.get_uploads('file')
blob_info = upload_files[0]
f = blob_info.open() # Return a BlobReader
content = f.read() # Read the entire file content into memory

You can use the Drive SDK to save file on Google Drive, you can find a sample app for Google App Engine here

Upvotes: 1

Related Questions