def __getBlob(cls, _key):
		""" Private method that gets blob content
			param @key is String
			return tuple (value, tll)
		"""
		if not _key is None:

			_clau = cls.__getBlobkey(_key)
			if not _clau is None:
				bi =  blobstore.get(_clau)
				br = bi.open()
				value = br.read()
				return cls.__checkIfExpired(value);
			else:
				z=0
				_clau = cls.__getBlobkey(_key+"_"+str(z))
				s=[]
				while not _clau is None:
					bl = blobstore.get(_clau)
					br = bl.open()
					s.append(br.read())
					z=z+1
					_clau = cls.__getBlobkey(_key+"_"+str(z))

				if z>0:	
					value = "".join(s)
					return cls.__checkIfExpired(value);

				else:
					return (None,None)
		else:
			return (None,None)		
Exemplo n.º 2
0
	def post(self):
		user = users.get_current_user()
		minIndex = int(self.request.get("minIndex"))
		maxIndex = int(self.request.get("maxIndex"))
		userID = self.request.get("userID")
		query = UserScreenshot.query(UserScreenshot.index >= minIndex,
			                         UserScreenshot.index <  maxIndex,
			                         ancestor=ndb.Key('UserCollection', userID)
			                         ).order(UserScreenshot.index)

		results = query.fetch(None)
		images = []
		for entry in results:
			blob_key = entry.blob_key
			blobstore.get(blob_key)
			reader = blobstore.BlobReader(blob_key)
			image = Image.open(reader)
			image.load()
			images.append(image)

		p = ScreenshotParser()
		cards = p.getCardsFromImages(images)
		for i in range(0, len(results)):
			# Bit of a fudge here, could get the ScreenshotParser to give us how many cards per image
			results[i].cards = ""
			for j in range(i * 8, min(i*8 + 8, len(cards))):
				results[i].cards += str(cards[j].toDict()) + "\n"
			results[i].cards = results[i].cards[:-1]    # Remove last newline
			blobstore.delete(results[i].blob_key)
			results[i].processed = True
			results[i].put()
		return
Exemplo n.º 3
0
    def post(self):
        user = users.get_current_user()
        minIndex = int(self.request.get("minIndex"))
        maxIndex = int(self.request.get("maxIndex"))
        userID = self.request.get("userID")
        query = UserScreenshot.query(UserScreenshot.index >= minIndex,
                                     UserScreenshot.index < maxIndex,
                                     ancestor=ndb.Key('UserCollection',
                                                      userID)).order(
                                                          UserScreenshot.index)

        results = query.fetch(None)
        images = []
        for entry in results:
            blob_key = entry.blob_key
            blobstore.get(blob_key)
            reader = blobstore.BlobReader(blob_key)
            image = Image.open(reader)
            image.load()
            images.append(image)

        p = ScreenshotParser()
        cards = p.getCardsFromImages(images)
        for i in range(0, len(results)):
            # Bit of a fudge here, could get the ScreenshotParser to give us how many cards per image
            results[i].cards = ""
            for j in range(i * 8, min(i * 8 + 8, len(cards))):
                results[i].cards += str(cards[j].toDict()) + "\n"
            results[i].cards = results[i].cards[:-1]  # Remove last newline
            blobstore.delete(results[i].blob_key)
            results[i].processed = True
            results[i].put()
        return
Exemplo n.º 4
0
    def get(self):
        photo_key = self.request.get('img_id')

        blobinfo = blobstore.get(photo_key)

        if not blobstore.get(photo_key):
            self.error(404)
        else:
            self.send_blob(photo_key, blobinfo.content_type)
Exemplo n.º 5
0
    def get(self, blob_key):
        if blob_key:
            blob_info = blobstore.get(blob_key)
            if blobstore.get(blob_key):
                self.send_blob(blob_key)
                return

        # Either "id" wasn't provided, or there was no image with that ID
        # in the datastore.
        self.error(404)
 def get(self, blob_key):
     blob_key = str(urllib.unquote(blob_key))
     if not blobstore.get(blob_key):
         logging.error("we didnt get it on the first try")
         blob_key = str(urllib.unquote(blob_key))
         if not blobstore.get(blob_key):
             self.error(404)
             logging.error("we didnt get it on the second try either")
     else:
         self.send_blob(blobstore.BlobInfo.get(blob_key))
Exemplo n.º 7
0
    def get(self):
        # Get the all user pics
        pics = Image.get_all_Images()
        params = {}
        if self.session.get('Error_Message'):
            params = {
                'Error_Message': str(self.session.get('Error_Message'))
            }
        if self.session.get('mail'):
            mail = self.session.get('mail')
            params.update({
                'log': "", 'logged': "none"
            })
        else:
            mail = ''
            params.update({
                'log': "none", 'logged': ""
            })
        self.session['Error_Message'] = None
        page = template.render('templates/Home_Header.html', params)
        if not pics:
            self.error(404)
        else:
            for pic in pics:
                if not blobstore.get(pic.blob_key):
                    logging.error('oops something went Terribly wrong.')
                else:
                    key = blobstore.get(pic.blob_key)
                    blob_info = blobstore.BlobInfo.get(pic.blob_key)
                    # This Code Fails in Production
                    url = '/view_photo/' + str(pic.blob_key)
                    comments = Comment.get_Detail(pic.key)
                    context = {'id': pic.key.id(), 'Name': pic.name,
                               'url': url, 'user': pic.author,
                               'comments': comments, 'nlikes': pic.Like,
                               'ndislikes': pic.Dislike,
                               'email': mail
                               }
                    if blob_info.content_type in image_types:
                        page = page + \
                            template.render(
                                'templates/Home_Form_Image.html', context)
                    elif blob_info.content_type in video_types:
                        page = page + \
                            template.render(
                                'templates/Home_Form_Video.html', context)
                    else:
                        logging.error("Something is Missed" + str(pic.id))

            page = page + template.render('templates/Home_footer.html', {})
            self.response.write(page)
Exemplo n.º 8
0
	def view( self, *args, **kwargs ):
		"""
			View or download a file.
		"""
		try:
			return super(File, self).view(*args, **kwargs)
		except (errors.NotFound, errors.NotAcceptable, TypeError) as e:
			if len(args) > 0 and blobstore.get(args[0]):
				raise errors.Redirect("%s/download/%s" % (self.modulePath, args[0]))
			elif len(args) > 1 and blobstore.get(args[1]):
				raise errors.Redirect("%s/download/%s" % (self.modulePath, args[1]))
			elif isinstance( e, TypeError ):
				raise errors.NotFound()
			else:
				raise e
Exemplo n.º 9
0
 def get(self, photo_key):
     logging.error("in blbosend")
     if not blobstore.get(photo_key):
         logging.error('going here')
         self.error(500)
     else:
         self.send_blob(photo_key)
Exemplo n.º 10
0
	def post(self):
		resource = self.request.get('resource')
		blob_info = blobstore.get(resource)
		blob_info.delete()
		self.response.headers['Content-Type'] = 'text/html'
		self.response.write('<h1>Delete Done</h1>')
		self.response.write('<a href="%s">Main Page</a>' %('/'))
Exemplo n.º 11
0
def img(blob_key):
    """ Serve an uploaded image """

    blob_info = blobstore.get(blob_key)
    response = make_response(blob_info.open().read())
    response.headers['Content-Type'] = blob_info.content_type
    return response
Exemplo n.º 12
0
    def send_blob_with_watermark(self, blob_key_or_info, watermark=""):
        if isinstance(blob_key_or_info, blobstore.BlobInfo):
            blob_key = blob_key_or_info.key()
            blob_info = blob_key_or_info
        else:
            blob_key = blob_key_or_info
            blob_info = blobstore.get(blob_key)

        if not blob_info:
            self.redirect(self.URL_PHOTO_NOT_FOUND)

        key = "blob_cache_%s_%s" % (blob_key, watermark)
        image_data = memcache.get(key)
        if not image_data:
            blob_reader = blobstore.BlobReader(blob_key)
            image_data = ccPhotoRequestHandler.create_watermark(
                blob_reader.read(),
                watermark=model.SITE_SETTINGS.watermark_img,
                position=model.SITE_SETTINGS.watermark_position,
                opacity=model.SITE_SETTINGS.watermark_opacity
                )
            blob_reader.close()
            if image_data:
                try:
                    memcache.set(key, image_data)
                except:
                    pass
            else:
                self.redirect(self.URL_PHOTO_NOT_FOUND)

        self.response.headers['Content-Type'] = utils.ImageMime.PNG
        self.response.out.write(image_data)
Exemplo n.º 13
0
def serve_work(request, photo_key):
    blob = blobstore.get(photo_key)
    if not blob:
        raise Http404
    else:
        return HttpResponse(blobstore.BlobReader(blob.key()).read(),
                            content_type=blob.content_type)
Exemplo n.º 14
0
  def get(self):
    greets = Photo.query(Photo.owner == owner).fetch()

    url=[]
    for greeting in greets:
      
      
      blob_key = blobstore.get(str(greeting.image))

      img = images.Image(blob_key=blob_key)


      info = {
        "lien":    images.get_serving_url(blob_key),
        "titre": greeting.titre,
        "description":  greeting.description,
        }
    
      url.append(info)
      

    #self.response.out.write(url[0])


    
    template = JINJA_ENVIRONMENT.get_template('portfolio.html')
    template_values = {
            'url': url,
            
        }
    self.response.write(template.render(template_values ))
Exemplo n.º 15
0
def download(bkey):

    blob_info = blobstore.get(bkey)

    response = make_response(blob_info.open().read())
    response.headers['Content-Type'] = blob_info.content_type
    return response
Exemplo n.º 16
0
 def get(self,*args,**kargs):
    
         #current_user =self.auth.get_user_by_session()
         user_db = model.user.OurUser.query().fetch()
         user1=self.auth.get_user_by_session()
         role=self.user_model.get_by_id(user1['user_id']).role.get().role
         
         user = self.user
         
         if user.blob_key:
              user_image= blobstore.get(user.blob_key)
         
         else :
              user_image=""
         
         
         logging.info(user_image)
         
         
      #   image_key=self.send_blob(self.OurUser.)
         
         upload_url = blobstore.create_upload_url('/admin/profile') 
         
     #    self.response.headers['Content-Type'] = 'image/png'
        
         
         self.render_template("admin_new/profile.html",{'user_image':user.blob_key,'permission':'success', 'user_db':user_db, 'role':role,"upload_url":upload_url})
Exemplo n.º 17
0
 def get(self, blob_key):
     if not blobstore.get(blob_key):
         self.error(404)
         return
     else:
         resource = str(urllib.unquote(blob_key))
         self.send_blob(blob_key)
Exemplo n.º 18
0
def migrate(image):
	"""Copies blobs stored in Blobstore over to a GCS bucket.

	Args:
		image: main.Image instance representing a single entity in the Datastore.

	This does not delete migrated (old) blobs so it is safe to run the job
	multiple times.
	"""
	if image.blob_key and not image.gs_key:
		blob_info = blobstore.get(image.blob_key)
		if not blob_info:
			image.blob_key = None
		else:
			gs_key = '/'.join(['', BUCKET, blob_info.filename])
			try:
				gcs.stat(gs_key)
			except gcs.NotFoundError:
				reader = blobstore.BlobReader(blob_info)
				with gcs.open(gs_key, 'w', content_type=blob_info.content_type) as f:
					while True:
						data = reader.read(1024**2)
						if not data:
							break
						f.write(data)
			blob_gs_key = blobstore.create_gs_key('/gs'+gs_key)
			image.url = images_api.get_serving_url(blob_gs_key, secure_url=True)
			image.gs_key = gs_key
		yield op.db.Put(image)
		if image.gs_key:
			yield op.counters.Increment('Migrated')
Exemplo n.º 19
0
    def get(self, photo_key):
        print "ViewPhotoHandler"

        if not blobstore.get(photo_key):
            self.error(404)
        else:
            self.send_blob(photo_key)
Exemplo n.º 20
0
 def get(self, blobkey):
     blob_key = str(urllib.unquote(blobkey))
     if not blobstore.get(blob_key):
         self.error(404)
         return
     
     self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=False)
Exemplo n.º 21
0
    def fetch_cached_thumbnail(cls, cached_key):
        blob_info = blobstore.get(
            blobstore.create_gs_key("/gs{0}".format(cached_key)))

        if blob_info:
            with blob_info.open() as f_blob:
                return f_blob.read()
Exemplo n.º 22
0
    def get(self):  # Handles addition of data into ndb
        self.response.headers['Content-Type'] = 'text/html'
        user = users.get_current_user()
        data = 0
        print('as')
        # Checking if user is logged in
        if user:
            main_header = 'Welcome to your DropBox'
            login_logout = 'Logout'
            login_logout_url = users.create_logout_url(self.request.uri)
            # Filter directories of current user.
            file_list = FileModel.query(FileModel.createdBy == user.user_id()).fetch()
            for each_file in file_list:
                blob_key = each_file.blob
                blob_info = blobstore.get(blob_key)
                data = data + blob_info.size
            print data
        else:
            main_header = 'Please Login to Access This Page..!!'  # Error message to indicate user not logged in.
            login_logout = 'Login'
            login_logout_url = users.create_login_url(self.request.uri)

        template_values = {
            'main_header': main_header,
            'login_logout': login_logout,
            'login_logout_url': login_logout_url,
            'user': user,
            'data': data
        }

        template = JINJA_ENVIRONMENT.get_template('data.html')
        self.response.write(template.render(template_values))
Exemplo n.º 23
0
 def size(self, name):
     blob_key = self._blobkey(name)
     blobinfo = blobstore.get(blob_key)
     if blobinfo:
         return blobinfo.size
     else:
         raise Exception("object does not exist at %s" % name)
Exemplo n.º 24
0
 def get(self,*args,**kargs):
    
         #current_user =self.auth.get_user_by_session()
         user_db = OurUser.query().fetch()
         user1=self.auth.get_user_by_session()
         role=self.user_model.get_by_id(user1['user_id']).role.get().role
         
         user = self.user
         
         if user.blob_key:
              user_image= blobstore.get(user.blob_key)
         
         else :
              user_image=""
         
         
         logging.info(user_image)
         
         
      #   image_key=self.send_blob(self.OurUser.)
         
         upload_url = blobstore.create_upload_url('/profile') 
         
     #    self.response.headers['Content-Type'] = 'image/png'
        
         
         self.render_template("user_new/profile.html",{'user_image':user.blob_key,'permission':'success', 'user_db':user_db, 'role':role,"upload_url":upload_url})
Exemplo n.º 25
0
    def post(self):
        author = str(self.request.get('author'))
        blob_key = str(self.request.get('blob_key'))
        q = EntryIndex.all()
        q.filter("author =", users.User(author))
        q.filter("blob_key =", blob_key)
        if q.count() > 0:
            return

        def txn():
            entryindex = EntryIndex()
            entryindex.author = users.User(author)
            entryindex.blob_key = blob_key
            entryindex.put()

        db.run_in_transaction(txn)

        if not blobstore.get(blob_key):
            return
        else:
            blob_reader = blobstore.BlobReader(blob_key)
            data = blob_reader.read()
            t = xml.etree.ElementTree.fromstring(data)
            pre_lat, pre_long, pre_time, pre_alt, pre_heart = None, None, None, None, None
            t_dist = 0
            t_alt = 0
            rec = 0
            for e in t.getiterator():
                if e.tag.find("Time") > 0:
                    time = e.text
                if e.tag.find("LatitudeDegrees") > 0:
                    lat = float(e.text)
                if e.tag.find("LongitudeDegrees") > 0:
                    long = float(e.text)
                if e.tag.find("AltitudeMeters") > 0:
                    alt = float(e.text)
                if e.tag.find("HeartRateBpm") > 0:
                    heart = int(e[0].text)
                    if pre_lat != None:
                        delta = distance([lat, long], [pre_lat, pre_long])
                        if fabs(alt - pre_alt) >= 1.2:
                            t_alt = t_alt + fabs(alt - pre_alt)
                        t_dist += delta
                        taskqueue.add(url='/queue1',
                                      params={
                                          'author': author,
                                          'blob_key': blob_key,
                                          'lat': lat,
                                          'long': long,
                                          'rec': rec,
                                          'heart': heart,
                                          'alt': alt,
                                          't_alt': t_alt,
                                          'dist': delta,
                                          't_dist': t_dist,
                                          'time': time
                                      },
                                      queue_name='queue1')
                    pre_lat, pre_long, pre_time, pre_alt, pre_hr = lat, long, time, alt, heart
                    rec = rec + 1
Exemplo n.º 26
0
def image_uploaded(request, key = None):

    if not key:
        util.HttpJsonResponse('', request)
    
    blob_info = blobstore.get(key)
    thumbnail_url = images.get_serving_url(blob_info.key(), size=80, crop=False)       
    
    small_url = images.get_serving_url(blob_info.key(), size=300, crop=False)               
    big_url   = "."#images.get_serving_url(blob_info.key(), size=1024, crop=False)                       

    results = { 'name':          blob_info.filename,
                'size':          blob_info.size,
                'thumbnail_url': thumbnail_url,
                'small_url':     small_url,
                'big_url':       big_url,                                        
                'delete_url':    '/image/remove/%s/' % blob_info.key(),   
                'delete_type':   'DELETE',
    }
    
    results = json.dumps([results])     
       
    logging.info("results: %s",results)
    
    return util.HttpJsonResponse(results, request)
Exemplo n.º 27
0
 def get(self, blob_key):
   if not blobstore.get(blob_key):
     self.error(404)
   else:
     self.response.headers["Cache-Control"] = "public, max-age="+str(30*24*60*60) # 30 days
     self.response.headers["Expires"] = (datetime.now() + timedelta(days=30)).strftime("%a, %d %b %Y %H:%M:%S GMT")
     self.send_blob(blob_key)
Exemplo n.º 28
0
 def get(self, resource):
   if not blobstore.get(resource):
           self.error(404)
   else:
           resource = str(urllib.unquote(resource))
           blob_info = blobstore.BlobInfo.get(resource)
           self.send_blob(blob_info)
Exemplo n.º 29
0
 def getBlob(self, blobKey):
  blob = blobstore.get(blobKey)
  if not blob:
   return self.error(404)
  with blob.open() as f:
   apkData = f.read()
  self.get(apkData)
Exemplo n.º 30
0
def img(blob_key):
    """ Serve an uploaded image """

    blob_info = blobstore.get(blob_key)
    response = make_response(blob_info.open().read())
    response.headers['Content-Type'] = blob_info.content_type
    return response
Exemplo n.º 31
0
    def upload_img(self, logo_url):
        image_url = logo_url
        filetype = 'image/%s' % image_url.split('.')[-1]
        if len(filetype) > 10:
            filetype = 'image/jpg'

        filename = image_url.split('/')[-1]
        raw_img = None

        result = urlfetch.fetch(image_url)
        if result.status_code == 200:
            raw_img = result.content
        else:
            return "error fetching URL"

        multipart_param = MultipartParam(
            'file', raw_img, filename=filename, filetype=filetype)
        datagen, headers = multipart_encode([multipart_param])
        upload_url = blobstore.create_upload_url('/upload_image')
        result = urlfetch.fetch(
            url=upload_url,
            payload="".join(datagen),
            method=urlfetch.POST,
            headers=headers)

        blob = blobstore.get(json.loads(result.content)["key"])

        self.logo = blob.key()
        self.put()
Exemplo n.º 32
0
 def get(self):
     existingFile = storage.FindBetaKey()
     if existingFile is not None:
         if blobstore.get(existingFile.id.key()):
             self.send_blob(existingFile.id, save_as=True)
         else:
             self.error(404)
Exemplo n.º 33
0
 def get(self, key, filename):
     if not blobstore.get(key):
         self.error(404)
     else:
         # Cache for the expiration time:
         self.response.headers["Cache-Control"] = "public,max-age=%d" % EXPIRATION_TIME
         self.send_blob(key, save_as=filename)
Exemplo n.º 34
0
    def upload_img(self, logo_url):
        image_url = logo_url
        filetype = 'image/%s' % image_url.split('.')[-1]
        if len(filetype) > 10:
            filetype = 'image/jpg'

        filename = image_url.split('/')[-1]
        raw_img = None

        result = urlfetch.fetch(image_url)
        if result.status_code == 200:
            raw_img = result.content
        else:
            return "error fetching URL"

        multipart_param = MultipartParam('file',
                                         raw_img,
                                         filename=filename,
                                         filetype=filetype)
        datagen, headers = multipart_encode([multipart_param])
        upload_url = blobstore.create_upload_url('/upload_image')
        result = urlfetch.fetch(url=upload_url,
                                payload="".join(datagen),
                                method=urlfetch.POST,
                                headers=headers)

        blob = blobstore.get(json.loads(result.content)["key"])

        self.logo = blob.key()
        self.put()
Exemplo n.º 35
0
    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)
Exemplo n.º 36
0
    def get(self, action, asset_key, filename=''):

        asset_key = ndb.Key(urlsafe=asset_key)
        asset = asset_key.get()
        if not asset:
            return self.error(404)
        if not asset.blob:
            return self.error(404)

        blob_info = blobstore.get(asset.blob)
        if not blob_info:
            return self.error(404)

        value = BlobReader(blob_info.key(), buffer_size=blob_info.size).read()

        # The code works with or without the following line.
        #value = unicode(value.decode('utf8')).encode('utf8')[0:-2]
        value = base64.b64decode(value.split('base64,')[1])

        self.response.body = value

        self.response.headers['Content-Type'] = str(blob_info.content_type)
        if action == 'get':
            self.response.headers['Content-Disposition'] = str('attachment; filename=' + blob_info.filename)

        return self.response
Exemplo n.º 37
0
	def download(self, blobKey, fileName = "", download = "", *args, **kwargs):
		"""
		Download a file.

		:param blobKey: The unique blob key of the file.
		:type blobKey: str

		:param fileName: Optional filename to provide in the header.
		:type fileName: str

		:param download: Set header to attachment retrival, set explictly to "1" if download is wanted.
		:type download: str
		"""
		if download == "1":
			fname = "".join([c for c in fileName if c in string.ascii_lowercase+string.ascii_uppercase + string.digits+".-_"])
			request.current.get().response.headers.add_header("Content-disposition", ("attachment; filename=%s" % (fname)).encode("UTF-8"))
		info = blobstore.get(blobKey)
		if not info:
			raise errors.NotFound()
		request.current.get().response.clear()
		request.current.get().response.headers['Content-Type'] = str(info.content_type)
		if self.blobCacheTime:
			request.current.get().response.headers['Cache-Control'] = "public, max-age=%s" % self.blobCacheTime
		request.current.get().response.headers[blobstore.BLOB_KEY_HEADER] = str(blobKey)
		return ""
Exemplo n.º 38
0
 def post_data(self, data, filename=None, mime_type=None):
     mime_type = mime_type or mimetypes.guess_type(filename)[0] if filename else None
     mime_type = mime_type or 'application/octet-stream'
     filename = filename or "{0}{1}".format(self.key_as_string, mimetypes.guess_extension(mime_type))
     url = blobstore.create_upload_url('/_bscs/data')
     params = []
     params.append(MultipartParam("file", filename=filename, filetype=mime_type, value=data))
     payload_generator, headers = multipart_encode(params)
     payload = str().join(payload_generator)
     key = None
     try:
         result = urlfetch.fetch(
             url=url, payload=payload, method=urlfetch.POST, headers=headers, deadline=10, follow_redirects=False
         )
         if "location" in result.headers:
             location = result.headers["location"]
             key = location[location.rfind("/") + 1:]
             return ndb.BlobKey(key) if key else None
         else:
             return None
     except Exception as e:
         logging.error(e)
         if key is not None:
             blob_info = blobstore.get(key)
             if blob_info is not None:
                 blob_info.delete()
         return None
Exemplo n.º 39
0
 def size(self, name):
     blob_key = self._blobkey(name)
     blobinfo = blobstore.get(blob_key)
     if blobinfo:
         return blobinfo.size
     else:
         raise Exception("object does not exist at %s" % name)
Exemplo n.º 40
0
		def render_photo(self, id):
			photo = Photo.get_by_id(int(id))
			blobKey = photo.blobKey
		
			if blobKey:
				blobinfo = blobstore.get(blobKey)
				
				if blobinfo:
					aspect = 'h'
					img = images.Image(blob_key=blobKey)
					img.rotate(180)
					thumbnail = img.execute_transforms(output_encoding=images.JPEG)
					if img.width > img.height:
						pass
					else:
						aspect = 'v'
					img = images.Image(blob_key=blobKey)
					if aspect == 'h':
						img.resize(width=505)
					else:
						img.resize(width=355)
					thumbnail = img.execute_transforms(output_encoding=images.JPEG)
					return thumbnail
				return
			self.error(404)
Exemplo n.º 41
0
  def post(self, data, check, mutator):
    Form = self._form(data)
    form = Form(request_data=data, data=data.POST,
        files=data.request.file_uploads)

    profile = self._profile(data)

    if not form.is_valid():
      # we are not storing this form, remove the uploaded blob from the cloud
      for blob_info in data.request.file_uploads.itervalues():
        blob_info.delete()

      # since this is a file upload we must return a 300 response
      error = form.errors[form.fileFieldName()]
      return self._r(data).to(
          self._urlName(data), extra=['error=%s' % error.as_text()])

    # delete the old blob, if it exists
    old_blob_key = getattr(profile.student_data, form.fileFieldName())
    if old_blob_key:
      blob_info = blobstore.get(old_blob_key)
      if blob_info:
        blob_info.delete()

    # write information about the new blob to the datastore
    blob_key = form.cleaned_data[form.fileFieldName()].key()
    setattr(profile.student_data, form.fileFieldName(), blob_key)
    profile.put()

    return self._r(data).to(self._urlName(data), validated=True)
Exemplo n.º 42
0
def serve(key):
    """ Endpoint for serving files

    Serves files from the blobstore by the given blob-key string

    Args:
        key: string value of BlobKey

    Returns:
        flask.Response object with the mimetype given by the BlobInfo
        entity

    Raises:
        NotFoundException in case of requested blog is nonexistent
    """

    try:
        blob_info = blobstore.get(key)
    except BlobNotFoundError:
        abort(404)

    response = Response(mimetype=blob_info.content_type, headers={
        'content-length': blob_info.size,
        'Content-Disposition': "attachment; filename=%s" % blob_info.filename
        })
    response.stream.writelines(_reader(blob_info))
    return response
def get_branding_blob_stream(branding):
    """A utility function to return a stream for the branding blob,
       mostly used with ZipFile

    Args:
        branding (Branding)

    Returns:
        a file-like object or None
    """

    if not branding:
        return

    stream = None
    if branding.blob_key:
        if DEBUG:
            blob_info = blobstore.get(branding.blob_key)
            if blob_info:
                stream = blob_info.open()
        else:
            filename = get_branding_cloudstorage_path(branding.hash, branding.user)
            try:
                stream = cloudstorage.open(filename, 'r')
            except cloudstorage.errors.NotFoundError:
                pass
    else:
        stream = StringIO(branding.blob)

    return stream
Exemplo n.º 44
0
    def post(self, data, check, mutator):
        Form = self._form(data)
        form = Form(request_data=data,
                    data=data.POST,
                    files=data.request.file_uploads)

        profile = self._profile(data)

        if not form.is_valid():
            # we are not storing this form, remove the uploaded blob from the cloud
            for blob_info in data.request.file_uploads.itervalues():
                blob_info.delete()

            # since this is a file upload we must return a 300 response
            error = form.errors[form.fileFieldName()]
            return self._r(data).to(self._urlName(data),
                                    extra=['error=%s' % error.as_text()])

        # delete the old blob, if it exists
        old_blob_key = getattr(profile.student_data, form.fileFieldName())
        if old_blob_key:
            blob_info = blobstore.get(old_blob_key)
            if blob_info:
                blob_info.delete()

        # write information about the new blob to the datastore
        blob_key = form.cleaned_data[form.fileFieldName()].key()
        setattr(profile.student_data, form.fileFieldName(), blob_key)
        profile.put()

        return self._r(data).to(self._urlName(data), validated=True)
Exemplo n.º 45
0
  def testGetDirectBlobstoreServe(self):
    self.mox.StubOutWithMock(util, 'GetInstance')
    self.mox.StubOutWithMock(blobstore, 'get')
    server = dump.DumpServer()
    server.error = self.mox.CreateMockAnything()
    server.send_blob = self.mox.CreateMockAnything()
    server.response = self.mox.CreateMockAnything()
    server.response.headers = {}
    mock_resource = self.mox.CreateMockAnything()
    mock_resource.blob = self.mox.CreateMockAnything()
    dummy_id = object()
    dummy_key = object()
    cache_headers = {
        'Expires': 'Sat, 19 Jul 2110 22:20:03 +0000',
        'Cache-Control': 'max-age=31557600, public'
    }

    # Simulate blobstore returning failure.
    util.GetInstance(model.Resource, dummy_id).AndReturn(mock_resource)
    mock_resource.blob.key().AndReturn(dummy_key)
    blobstore.get(dummy_key).AndReturn(None)
    server.error(httplib.NOT_FOUND)

    # Image resource.
    util.GetInstance(model.Resource, dummy_id).AndReturn(mock_resource)
    mock_resource.blob.key().AndReturn(dummy_key)
    blobstore.get(dummy_key).AndReturn(object())
    server.send_blob(dummy_key)

    # Model resource.
    util.GetInstance(model.Resource, dummy_id).AndReturn(mock_resource)
    mock_resource.blob.key().AndReturn(dummy_key)
    blobstore.get(dummy_key).AndReturn(object())
    server.send_blob(dummy_key, content_type=settings.COLLADA_MIME_TYPE)

    # Model-in-KMZ resource.
    util.GetInstance(model.Resource, dummy_id).AndReturn(mock_resource)
    mock_resource.blob.key().AndReturn(dummy_key)
    blobstore.get(dummy_key).AndReturn(object())
    server.send_blob(dummy_key, content_type=settings.KMZ_MIME_TYPE)

    self.mox.ReplayAll()

    server.GetResource(dummy_id)
    self.assertEqual(server.response.headers, {})

    mock_resource.type = 'image'
    server.GetResource(dummy_id)
    self.assertEqual(server.response.headers, cache_headers)

    mock_resource.type = 'model'
    server.GetResource(dummy_id)
    self.assertEqual(server.response.headers, cache_headers)

    mock_resource.type = 'model_in_kmz'
    server.GetResource(dummy_id)
    self.assertEqual(server.response.headers, cache_headers)
Exemplo n.º 46
0
 def get(self, audio_key):
     if not blobstore.get(photo_key):
         self.error(404)
     else:
         resource = str(urllib.unquote(audio_key))
         blob_info = blobstore.BlobInfo.get(resource)
         self.send_blob(blob_info, save_as=True)
         self.response.write(str(key))
Exemplo n.º 47
0
 def get_qr_code_url(self):
     try:
         if self.qr_code and blobstore.get(self.qr_code):
             return images.get_serving_url(self.qr_code)
         else:
             return ""
     except:
         return "http://check-me-in.biz/blobstore/images/" + str(self.qr_code)
Exemplo n.º 48
0
 def get(self, key, filename):
     if not blobstore.get(key):
         self.error(404)
     else:
         # Cache for the expiration time:
         self.response.headers['Cache-Control'] =\
             'public,max-age=%d' % EXPIRATION_TIME
         self.send_blob(key, save_as=filename)
    def get(self, file_id):
        file_id = self.request.get('photoID')
        file = File.get_by_id(long(file_id))

        if not blobstore.get(file.blob):
            self.error(404)
        else:
            self.send_blob(file.blob)
Exemplo n.º 50
0
    def get_blob(self, image_key):
        blob_info = blobstore.get(image_key)

        if blob_info:
            logging.info("fetching image for {}".format(image_key))
            return blobstore.fetch_data(image_key, 0, blob_info.size)
        else:
            raise cloudstorage.NotFoundError
Exemplo n.º 51
0
 def img_in_cache(self):
     """
         Returns True if the thumbnail image is in the cache
     """
     return blobstore.get(
         blobstore.create_gs_key(
             "/gs/greenday-project-v02-local.appspot.com/gd-yt-thumbs/{yt_id}/ytthumb-{yt_id}-{ms}"
             .format(yt_id=self.yt_id, ms=self.at_milliseconds)))
Exemplo n.º 52
0
    def thumbnailer(self, blob_key):
        blob_info = blobstore.get(blob_key)

        if blob_info:
            img = images.Image(blob_key=blob_key)
            img.resize(width=300, height=300)
            thumbnail = img.execute_transforms(output_encoding=images.PNG)
            return thumbnail
Exemplo n.º 53
0
    def get(self, file_key, file_name):
        self.response.headers['Content-Type'] = 'application/x-gzip'
        self.response.headers[
            'Content-Disposition'] = 'attachment; filename=' + str(file_name)

        if not blobstore.get(file_key):
            self.error(404)
        else:
            self.send_blob(file_key)
Exemplo n.º 54
0
 def get(self, file_key):
     email = get_user_email()
     if email:
         if not blobstore.get(file_key):
             self.error(404)
         else:
             self.send_blob(blobstore.BlobInfo.get(file_key), save_as=True)
     else:
         self.redirect('/')
Exemplo n.º 55
0
 def get(self, project_id):
     project_id = int(project_id)
     project = model.show_project(project_id)
     project_feed_key = project.feed
     project_feed_info = blobstore.BlobInfo(project.feed)
     if not blobstore.get(project_feed_key):
         self.error(404)
     else:
         self.send_blob(project_feed_info, save_as=True)
Exemplo n.º 56
0
 def exists(self, name):
     logging.debug("GCSStorage.exists() was called.")
     blob_key = self._blobkey(name)
     if blobstore.get(blob_key):
         logging.info("blobstore key %s exists" % str(blob_key))
         return True
     else:
         logging.info("blobstore key %s does not exist" % str(blob_key))
         return False
Exemplo n.º 57
0
 def deleteImages(self, request):
     # images = ImageUpload.query();
     id = int(request.id)
     imageKey = ImageUpload.get_by_id(id).key
     logging.debug('Deleting Image with ID: ' + request.id)
     blob = blobstore.get(imageKey.get().blob_key)
     blob.delete()
     imageKey.delete()
     return request