コード例 #1
0
ファイル: views.py プロジェクト: hm1021/webbattle
def post_comment(key):
	battle = Battle.get(key)
	now = datetime.now()
	if request.form.has_key('leftbox'):
		comment = request.form.get('leftbox')
		left_comment = Comment(parent=battle, comment=comment, author=users.get_current_user(), side="left", when=now)
		if request.files['left_image']:
			image_file = request.files['left_image']
			headers = image_file.headers['Content-Type']
			blob_key = parse_options_header(headers)[1]['blob-key']
			left_comment.blob_key = blob_key
			left_comment.image_url = images.get_serving_url(blob_key)
		left_comment.put()
		send_emails(key, comment)
	elif request.form.has_key('rightbox'):
		comment = request.form.get('rightbox')
		right_comment = Comment(parent=battle, comment=comment, author=users.get_current_user(), side="right", when=now)
		if request.files['right_image']:
			image_file = request.files['right_image']
			headers = image_file.headers['Content-Type']
			blob_key = parse_options_header(headers)[1]['blob-key']
			right_comment.blob_key = blob_key
			right_comment.image_url = images.get_serving_url(blob_key)
		right_comment.put()
		send_emails(key, comment)
	return left_right(key)
コード例 #2
0
ファイル: main.py プロジェクト: vishalsanfran/gcloud-apps
    def _create_note(self, user, title, content, attachments):

        note = Note(parent=ndb.Key("User", user.nickname()),
                    title=title,
                    content=content)
        note.put()

        if attachments:
            bucket_name = app_identity.get_default_gcs_bucket_name()
            for file_name, file_content in attachments:
                content_t = mimetypes.guess_type(file_name)[0]
                real_path = os.path.join('/', bucket_name, user.user_id(), file_name)

                with cloudstorage.open(real_path, 'w', content_type=content_t,
                                       options={'x-goog-acl': 'public-read'}) as f:
                    f.write(file_content.decode())

                key = blobstore.create_gs_key('/gs' + real_path)
                try:
                    url = images.get_serving_url(key, size=0)
                    thumbnail_url = images.get_serving_url(key, size=150, crop=True)
                except images.TransformationError, images.NotImageError:
                    url = "http://storage.googleapis.com{}".format(real_path)
                    thumbnail_url = None

                f = NoteFile(parent=note.key, name=file_name,
                             url=url, thumbnail_url=thumbnail_url,
                             full_path=real_path)
                f.put()
                note.files.append(f.key)

            note.put()
コード例 #3
0
    def get_urls_attach_files(self):
        result = []
        for key in self.attach_files:
            blob_info = blobstore.BlobInfo.get(key)
            filename =  blob_info.filename
            extensionsToCheck = ('.png', '.jpeg', '.jpg')
            if filename.lower().endswith(extensionsToCheck):
                image_url_200 = get_serving_url(key, 200)
                image_url_40 = get_serving_url(key, 40)
                image_url = get_serving_url(key, 1200)
            else:
                image_url = None
                image_url_200 = None
                image_url_40 = None

            return self.text
            di = {
                "image_url_200":image_url_200,
                "image_url_40":image_url_40,
                "image_url":image_url,
                "filename":filename,
                "key":str(key),
                "link_file":"/server?key="+str(key),
                "delete_url":'/uploads?key=' + str(key)
            }

            result.append(di)
        return result
コード例 #4
0
ファイル: gsimage.py プロジェクト: uve/onarena
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)
コード例 #5
0
def get_circle(circle_id):
    circle = db_session.query(Circle).filter_by(CircleID=circle_id,
                                                Deleted=False).first()

    if circle:
        circle_members = db_session.query(CircleMember).filter_by(
            CircleID=circle_id, Removed=False).all()
        members = list()

        for cm in circle_members:
            user = db_session.query(User).filter_by(UserID=cm.UserID).first()
            members.append(
                dict(memberUserID=user.UserID,
                     memberName=user.Name,
                     memberMobile=user.Mobile,
                     memberEmail=user.EmailID,
                     imageURL=images.get_serving_url(user.ImageKey,
                                                     secure_url=True)
                     if user.ImageKey else None,
                     isAdmin=cm.IsAdmin))

        return jsonify(status=1,
                       message='success',
                       circle=dict(circleID=circle_id,
                                   circleName=circle.CircleName,
                                   circleAgeDate=circle.AgeDate.isoformat(),
                                   imageURL=images.get_serving_url(
                                       circle.ImageKey, secure_url=True)
                                   if circle.ImageKey else None,
                                   members=[i for i in members]))

    return jsonify(status=0, message='Circle doesn\'t exists')
コード例 #6
0
ファイル: main.py プロジェクト: marknigh/warson-woods-sitting
 def post(self):
     user = users.get_current_user()
     sitter = Sitter.query(Parent.user == user).get()
     upload_file = self.get_uploads('upload')
     if sitter:
         sitter.name = self.request.get('name')
         sitter.email = user.email()
         sitter.phone = self.request.get('mobile')
         sitter.address = self.request.get('address')
         sitter.city = self.request.get('city')
         sitter.state = self.request.get('state')
         sitter.zip = self.request.get('zip')
         # sitter.age = int(self.request.get('age')) #removed age as a property. Must be calculated.
         sitter.grade = self.request.get('grade')
         sitter.school = self.request.get('school')
         #sitter.pet = self.request.get('pet') != ''
         #sitter.house = self.request.get('house') != ''
         #sitter.children = self.request.get('children') != ''
         type = self.request.get('type', allow_multiple=True)
         if 'pet' in type:
             sitter.pet = True
         if 'children' in type:
             sitter.children = True
         if 'house' in type:
             sitter.house = True
         sitter.notes = self.request.get('notes')
         sitter.certified = self.request.get('certified') != ''
         sbday = self.request.get('bday')
         sitter.birthdate = datetime.strptime(sbday, '%m/%d/%Y').date()
         if upload_file:
             blob_info = upload_file[0]
             sitter.picture = blob_info.key()
             sitter.pictureurl = images.get_serving_url(str(blob_info.key()))
         sitter.put()
     else:
         if upload_file:
             blob_info = upload_file[0]
             picture = blob_info.key()
             pictureurl = images.get_serving_url(str(blob_info.key()))
             sitter = Sitter(user=user, picture=picture, pictureurl=pictureurl)
         #pet = self.request.get('pet') != ''
         #house = self.request.get('house') != ''
         #children = self.request.get('children') != ''
         type = self.request.get('type', allow_multiple=True)
         if 'pet' in type:
             pet = True
         if 'children' in type:
             children = True
         if 'house' in type:
             house = True
         certified = self.request.get('certified') != ''
         sbday = self.request.get('bday')
         birthdate = datetime.strptime(sbday, '%m/%d/%Y').date()
         # age = int(self.request.get('age'))
         sitter=Sitter(user=user, name=self.request.get('name'),
                email = user.email(), phone=self.request.get('mobile'), address=self.request.get('address'),
                city=self.request.get('city'), state=self.request.get('state'), zip=self.request.get('zip'), birthdate=birthdate,
                school=self.request.get('school'), pet=pet, house=house, children=children, notes=self.request.get('notes'), certified=certified, grade=self.request.get('grade'))
         sitter.put()
     self.redirect('/')
コード例 #7
0
ファイル: main.py プロジェクト: yashiy/MakeUpReviews
 def get(self):
     #makeup_query = MakeUpPics.query(ancestor=PARENT_KEY).order(-MakeUpPics.last_touch_date_time)
     print(self.request.get("sortby"))
     upload_url = blobstore.create_upload_url('/insertpic')
     if(self.request.get("sortby") == "pop"):
         
         makeup_query = MakeUpPics.query(ancestor=PARENT_KEY)
         makeup_list = makeup_query.fetch()
         images_list = []
         makeup_list = sorted(makeup_list, key=lambda makeup: -makeup.agree-makeup.disagree)
         for item in makeup_list:
             if item.image_url == "":
                 logging.warning(item.image_url_local)
                 images_list.append(images.get_serving_url(item.image_url_local))
             else:
                 images_list.append(item.image_url)
     else:
         images_list = []
         makeup_query = MakeUpPics.query(ancestor=PARENT_KEY).order(-MakeUpPics.last_touch_date_time)
         for item in makeup_query:
             if item.image_url == "":
                 images_list.append(images.get_serving_url(item.image_url_local))
             else:
                 images_list.append(item.image_url)
         makeup_list = makeup_query.fetch()
     template = jinja_env.get_template("templates/mainpage.html")
     
     self.response.write(template.render({"makeup_query": makeup_list, "upload_url": upload_url, "images_list":images_list}))
コード例 #8
0
ファイル: models.py プロジェクト: sovcn/paradigm-old
 def url(self, width=None, height=None):
     if width or height:
         return get_serving_url(blob_key=self.file.file.blobstore_info.
                                _BlobInfo__key) + "=s" + str(width)
     else:
         return get_serving_url(
             blob_key=self.file.file.blobstore_info._BlobInfo__key)
コード例 #9
0
ファイル: route_api.py プロジェクト: GAEBlog/blog
    def _post_update_images(self, par):

        key = self._pl["key"]
        which = self._pl["which"]
        url = self._pl["url"]
        parcontent = Content.get_by_key_name(key)
        content = parcontent.editing

        if which == "mainimage":
            image = Image.get_by_id(int(url))

            content.mainimage = image
            content.imagepath = None  # so reset the path

            if content.thumb == None:
                content.thumb = images.get_serving_url(image.blob_key, 150)

        elif which == "thumb":
            content.thumb = url

        elif which == "reset_thumb":
            image = content.mainimage
            if image:
                content.thumb = images.get_serving_url(image.blob_key, 150)

        elif which == "main_url":
            content.imagepath = url  # so reset the path

        elif which == "thumb_url":
            content.thumb = url  # so reset the path

        content.put()

        # respond with a good code
        self._req.draw_code()
コード例 #10
0
ファイル: meme.py プロジェクト: thejasvibhat/smashed
    def get(self):
        tag = self.request.get('tag',default_value="auto")
        tags = tag.split(',')
        mode = self.request.get('mode',default_value="public")
        oLimit = int(self.request.get("limit", default_value="10"))
        oOffset = int(self.request.get("offset", default_value="0"))
        if tag == "auto":
            if mode == "public":
                meme_query = MemeDb.query(MemeDb.mode == 'public').order(-MemeDb.date)
            else:
                meme_query = MemeDb.query(MemeDb.userid == self.user_id).order(-MemeDb.date)
        else:
            if mode == "public":
                meme_query = MemeDb.query(MemeDb.mode == 'public').order(-MemeDb.date)
                meme_query = meme_query.filter(MemeDb.tags.IN(tags));
            else:
                meme_query = MemeDb.query(MemeDb.userid == self.user_id).order(-MemeDb.date)  
                meme_query = meme_query.filter(MemeDb.tags.IN(tags));
            
        memes = meme_query.fetch(oLimit,offset=oOffset)

        for meme in memes:
            meme.thumburl = images.get_serving_url (meme.resid, size=100)
            meme.url = images.get_serving_url (meme.resid, size=500)

        path = os.path.join(os.path.dirname(__file__), 'templates/ohskel-list.tmpl')
        tclass = Template.compile (file = path)
        template_values = {"memes" : memes}

        self.response.headers['Content-Type'] = 'text/xml'
        self.response.write (tclass (searchList=template_values))
コード例 #11
0
ファイル: route_api.py プロジェクト: Carhoots/blog
    def _post_update_images(self, par):
        
        key = self._pl['key']
        which = self._pl['which']
        url = self._pl['url']
        parcontent = Content.get_by_key_name(key)
        content = parcontent.editing
        
        if which == "mainimage":
            image = Image.get_by_id(int(url))
            
            content.mainimage = image
            content.imagepath = None   # so reset the path    

            if content.thumb == None:
                content.thumb = images.get_serving_url(image.blob_key, 150)

        elif which == "thumb":
            content.thumb = url

        elif which == "reset_thumb":
            image = content.mainimage
            if image:
                content.thumb = images.get_serving_url(image.blob_key, 150) 
            
        content.put()
コード例 #12
0
ファイル: main.py プロジェクト: UTWebApplication6/sample3
    def get(self):
        if self.request.get("id1") and  self.request.get("id2"):
            img1=ImgData.get_by_id(long(self.request.get("id1")))
            img2=ImgData.get_by_id(long(self.request.get("id2")))
            if img1 and img2:
                url1=images.get_serving_url(img1.blob_key)
                url2=images.get_serving_url(img2.blob_key)
                print "##############"
                print url1
                filePointer = urllib2.urlopen(url1)
                data1 = filePointer.read()
                filePointer.close()
                filePointer = urllib2.urlopen(url2)
                data2 = filePointer.read()
                filePointer.close()

                layer1= Image.open(StringIO(data1))
                layer2= Image.open(StringIO(data2))
                images.delete_serving_url(img1.blob_key)
                images.delete_serving_url(img2.blob_key)
                c=Image.new('RGBA',layer1.size,(255,255,255,0))
                c.paste(layer2,(0,0),layer2)
                #newimg=Image.alpha_composite(layer1,c)
                layer1.paste(layer2,(0,0),layer2)
                #newimg.im_feeling_lucky()
                output= StringIO()
                layer1.save(output,format='png')
                imageLayer =output.getvalue()
                output.close()
                self.response.headers['Content-Type']='image/png'
                self.response.out.write(imageLayer)
            else:
                self.error(404)
        else:
            self.error(404)
コード例 #13
0
    def _create_note(self, user, title, content, attachments):

        note = Note(parent=ndb.Key("User", user.nickname()),
                    title=title,
                    content=content)
        note.put()

        if attachments:
            bucket_name = app_identity.get_default_gcs_bucket_name()
            for file_name, file_content in attachments:
                content_t = mimetypes.guess_type(file_name)[0]
                real_path = os.path.join('/', bucket_name, user.user_id(), file_name)

                with cloudstorage.open(real_path, 'w', content_type=content_t,
                                       options={'x-goog-acl': 'public-read'}) as f:
                    f.write(file_content.decode())

                key = blobstore.create_gs_key('/gs' + real_path)
                try:
                    url = images.get_serving_url(key, size=0)
                    thumbnail_url = images.get_serving_url(key, size=150, crop=True)
                except images.TransformationError, images.NotImageError:
                    url = "http://storage.googleapis.com{}".format(real_path)
                    thumbnail_url = None

                f = NoteFile(parent=note.key, name=file_name,
                             url=url, thumbnail_url=thumbnail_url,
                             full_path=real_path)
                f.put()
                note.files.append(f.key)

            note.put()
コード例 #14
0
ファイル: main.py プロジェクト: OlexandrI/pyside
	def returnAllJSON(self):
		results = []
		fils = BlobInfo.all()
		for record in fils:
			blob_key = str(record.key())
			result = {}
			result['key'] = blob_key
			result['name'] = record.filename
			result['type'] = record.content_type
			result['size'] = record.size
			result['deleteType'] = 'DELETE'
			result['deleteUrl'] = self.request.host_url +'/?key=' + urllib.quote(blob_key, '')
			if (IMAGE_TYPES.match(result['type'])):
				try:
					result['url'] = images.get_serving_url(blob_key, size=1024, crop=True, secure_url=None)
					result['thumbnailUrl'] = images.get_serving_url(blob_key, size=240, crop=True, secure_url=None)
					result['thumbnailUrl2'] = images.get_serving_url(blob_key, size=120, crop=True, secure_url=None)
				except:  # Could not get an image serving url
					pass
			if not 'url' in result:
				result['url'] = self.request.host_url +\
					'/' + blob_key + '/' + urllib.quote(
						result['name'].encode('utf-8'), '')
			results.append(result)
		#result = {'files': results}
		s = json.dumps(results, separators=(',', ':'))
		redirect = self.request.get('redirect')
		if redirect:
			return self.redirect(str(
				redirect.replace('%s', urllib.quote(s, ''), 1)
			))
		if 'application/json' in self.request.headers.get('Accept'):
			self.response.headers['Content-Type'] = 'application/json'
		self.response.write(s)
コード例 #15
0
ファイル: kaixo.py プロジェクト: imaira92/kaixoMundua
    def post(self):        
        if self.session.get('email'):
            query = Album.query(ancestor= ndb.Key(User,self.session.get('email'))).fetch()
            
            self.response.out.write(FORM_VER_FOTOS_ALBUM_HTML)
            self.response.out.write('<select name = "album_name">')
            
            for album in query:
                self.response.out.write('<option value="%s">%s</option>' % (album.nombre,album.nombre))

            self.response.out.write('</select>')
            self.response.out.write(VER_FOTOS_ALBUM_HTML)
            list = cgi.escape(self.request.get("tags")).split(",")
                     
            query = Image.query(ancestor= ndb.Key(User,self.session.get('email'), Album, cgi.escape(self.request.get('album_name')) )).fetch()
                
            for foto in query:
                if get_first(list):
                    for tag in list:
                        
                        if tag.strip() in foto.tags:
                            img = images.get_serving_url(foto.foto_key, size=None, crop=False, secure_url=True)
                            self.response.write('<tr><td><img src=%s width="400px" height="400px"></img></tr></td>' % img +'<td><p>Subida por %s ' % foto.user + '</td></tr>')
                            return
                else:
                    img = images.get_serving_url(foto.foto_key, size=None, crop=False, secure_url=True)
                    self.response.write('<tr><td><img src=%s width="400px" height="400px"></img></tr></td>' % img +'<td><p>Subida por %s ' % foto.user + '</td></tr>')
                    
        else:
            self.redirect("/login")
            self.response.write('Debes loguearte de nuevo')
コード例 #16
0
 def post(self):
   upload_files = self.get_uploads('gallery_images')
   id = self.request.get("team_id")
   team = Team.get_by_id(long(id))
   redirect_url = self.uri_for('view-team', team_id = id )
   logger.info('Uploaded files: ' + str(upload_files))
   #logger.info('Get Request: ' + str(self.request.get()))
   if upload_files is not None and len(upload_files) > 0:
     files_count = len(upload_files)
     logger.info('no of files uploaded ' + str(files_count))
     for x in xrange(files_count):
       blob_info = upload_files[x]
       media_obj = Media()
       #media_obj.name = self.form.media.__getitem__(x).data['name']
       media_obj.type = constants.PHOTO
       media_obj.status = True
       #media_obj.primary = self.form.media.__getitem__(x).data['primary']
       media_obj.link = blob_info.key()
       media_obj.url = images.get_serving_url(blob_info.key())
       media_obj.entity_id = team.key
       media_obj.entity_type = constants.TEAM
       logger.info('Upload file detail: ' + str(media_obj))
       #self.mediaDao.persist(media_obj)
       media_obj.put()
       logger.info('Link to picture file ' + images.get_serving_url(media_obj.link))    
   return self.redirect(redirect_url)
コード例 #17
0
ファイル: connexus.py プロジェクト: ruthst/ee_382v_apt_vbill
  def get(self, resource):
		print 'entered serve'
		resource = str(urllib.unquote(resource))
		blob_info = blobstore.BlobInfo.get(resource)
		print images.get_serving_url(blob_info.key())
		img_url = images.get_serving_url(blob_info.key())
		self.send_blob(blob_info)
コード例 #18
0
ファイル: main.py プロジェクト: abhimir/dropmocks
  def post(self):
    id = self.request.get('id')
    edit_key = self.request.get('key')
    filename = self.request.get('filename')

    import logging
    logging.info(filename)

    mocklist = dbMockList(id)
    if mocklist.edit_key != edit_key:
      self.response.out.write('invalid edit key')
      return

    mock = Mock()
    mock.name = filename
    if self.request.POST:
      # FormData
      upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
      blob_info = upload_files[0]
      mock.blob_key = blob_info.key()
      image = images.Image(blob_key=str(blob_info.key()))
      image.horizontal_flip()
      image.execute_transforms()
      
      if image.width > 1280:
        mock.serving_url = images.get_serving_url(str(blob_info.key()), 1280)
      else:
        mock.serving_url = images.get_serving_url(str(blob_info.key()))
    else:
      # Firefox3
      mock.data = self.request.body
    mock.mocklist = mocklist
    mock.put()

    self.redirect("/api/uploaded/?id=%s" % mock.get_id())
コード例 #19
0
ファイル: main.py プロジェクト: sergioech/apothemsolutions
    def post(self):
        uploads = self.get_uploads()

        bulk_upload = False
        slides_details = diccionarios_CNBV.definiciones['bulk_slide_import']

        i = 0
        for upload in uploads:

            if bulk_upload:
                slide = Slide(
                    pic_key=upload.key(),
                    pic_url=images.get_serving_url(blob_key=upload.key()),
                    lead=slides_details[upload.filename][0],
                    tags=slides_details[upload.filename][1],
                    number=i,
                    doc_name='Default')
            else:
                slide = Slide(
                    pic_key=upload.key(),
                    pic_url=images.get_serving_url(blob_key=upload.key()),
                    lead='Lead',
                    tags=[],
                    number=i,
                    doc_name='Default')
            slide.put()
            i += 1
        self.redirect('/DeckEditor')
コード例 #20
0
 def get_photos(self,
                keys,
                published_filter=True,
                limit=settings.photos_per_page,
                offset=0,
                src_width=settings.photo_s_w,
                src_height=settings.photo_s_h):
     try:
         if keys:
             photos = Photo.get(keys[offset:limit + offset])
         else:
             query = Photo.all()
             query.order('-created')
             photos = query.fetch(limit, offset)
         photos_extended = []
         for photo in photos:
             if (published_filter
                     and photo.published) or not published_filter:
                 self.templateapi.manipulator.formater(
                     photo, [{
                         'name': 'description',
                         'type': 'unicode'
                     }])
                 if settings.photo_get_serving_url:
                     if src_width > src_height:
                         src_size = src_width
                     else:
                         src_size = src_height
                     photo.src = images.get_serving_url(
                         photo.photo.key(), src_size)
                     photo.view_url = images.get_serving_url(
                         photo.photo.key(), settings.photo_l)
                 else:
                     photo.src = self.templateapi.get_redirect(
                         settings.photo_output_url_string %
                         str(photo.photo.key()), 'add_multi',
                         [{
                             'query': 'width',
                             'value': src_width
                         }, {
                             'query': 'height',
                             'value': src_height
                         }])
                     photo.view_url = self.templateapi.get_redirect(
                         settings.photo_output_url_string %
                         str(photo.photo.key()), 'add_multi',
                         [{
                             'query': 'width',
                             'value': settings.photo_l_w
                         }, {
                             'query': 'height',
                             'value': settings.photo_l_h
                         }])
                 photo.like_url = self.templateapi.get_redirect(
                     settings.photo_view_url_string % str(photo.key().id()))
                 photos_extended.append(photo)
         return photos_extended
     except:
         return None
コード例 #21
0
def upload():
    """
    Endpoint after GCS upload
    :return: JSON --> filelink, filename, thumb
    """
    if request.method == 'POST':
        request_file = request.files['file']

        # Creates the options for the file
        header = request_file.headers['Content-Type']
        parsed_header = parse_options_header(header)

        # IF everything is OK, save the file
        if request_file:
            try:
                blob_key = parsed_header[1]['blob-key']
                blob_info = blobstore.get(blob_key)
                blob_key_object = blob_info._BlobInfo__key
                img_url = '/admin/file_serve/'+blob_key
                img_gallery = img_url

                # Check if is image and save a reference
                if blob_info.content_type in IMAGES_MIME:
                    img = Image(image_data=blob_info.open().read())

                    if img.height > 1600 or img.width > 1600:
                        img_gallery = get_serving_url(blob_key_object,
                                                      size=1600)

                        # Landscape
                        if img.height < img.width:
                            img_height = (img.height*1600)/img.width
                            img_width = 1600

                        # Portrait
                        else:
                            img_width = (img.width*1600)/img.height
                            img_height = 1600
                    else:
                        img_height = img.height
                        img_width = img.width

                    img_ref = ImageReference(filename=blob_info.filename,
                                             blob=blob_key_object,
                                             url=img_url,
                                             thumb=get_serving_url(blob_key_object, crop=True, size=200),
                                             gallery=img_gallery,
                                             height=img_height,
                                             width=img_width)
                    img_ref.put()

                return jsonify({"filelink": "/admin/file_serve/" + blob_key,
                                "filegallery": img_gallery,
                                "filename": "" + blob_info.filename,
                                "thumb": get_serving_url(blob_key, crop=True, size=200)})
            except Exception as e:
                logging.exception(e)
                return jsonify({"error": e})
コード例 #22
0
ファイル: dagkot.py プロジェクト: PeithVergil/dagkot
    def get_pictures(self):
        count = 0
        for picture in self.dagkot_pictures:
            count += 1

            if count == 1:
                yield images.get_serving_url(picture, 205, True)
            else:
                yield images.get_serving_url(picture, 50, True)
コード例 #23
0
	def handle_upload(self):
		results = []
		blob_keys = []
		stream_name = self.request.get('this_stream')
		print stream_name
		for name, fieldStorage in self.request.POST.items():
			# just got rid of fieldStorage requirements
			if name == 'this_stream':
				print 'just found hidden input'
				continue
			# what is fieldStorage?
			print 'in handle upload '
			print 'name is'
			print name
			print 'fieldStorage = ' 
			print type(fieldStorage)
			print fieldStorage
			result = {}
			# put img_info = {} here? fill in?!??? info for other pages
			img_info = {}
			result['name'] = re.sub(r'^.*\\','',fieldStorage.filename)
			result['type'] = fieldStorage.type
			result['size'] = self.get_file_size(fieldStorage.file)
			print 'size is'
			print result['size']
			print 'type is'
			print result['type']
			if self.validate(result):
				print 'passed file validate'
				blob_key = str(self.write_blob(fieldStorage.value, result))
				blob_keys.append(blob_key)
				result['deleteType'] = 'DELETE'
				result['deleteUrl'] = self.request.host_url+'/?key='+urllib.quote(blob_key,'')
				single_stream = ImageStream.query(ImageStream.stream_name == stream_name).fetch()
				upload_time = datetime.now()
				single_stream[0].info[stream_name]['stream_urls'].append((images.get_serving_url(blob_key), str(upload_time.date())))
				single_stream[0].info[stream_name]['stream_len'] += 1
				single_stream[0].put()
				time.sleep(0.1)
				print 'single_stream'
				print single_stream
				if (IMAGE_TYPES.match(result['type'])):
					try:
						result['url'] = images.get_serving_url(blob_key)
						result['thumbnailUrl'] = result['url']+THUMBNAIL_MODIFICATOR
						print 'SUCCESS'
					except:
						pass		

				if not 'url' in result:
					print 'what am I doing in here'
					result['url'] = self.request.host_url+'/'+blob_key+'/'+urllib.quote(result['name'].encode('utf-8'),'')

			results.append(result)
		#deferred.defer(cleanup, blob_keys, _countdown=EXPIRATION_TIME)
		return results
コード例 #24
0
    def get(self, product_id, product_name=False):

        product_obj = schema.Product.get_by_id(int(product_id))

        if product_obj.image:
            product_obj.image_url = get_serving_url(product_obj.image, 500)

        if product_obj != None:

            if product_obj.image:
                product_image_url = get_serving_url(product_obj.image, 300)
                product_obj.image_url = product_image_url
            else:
                product_obj.image_url = "/img/product_300x300.jpg"

            if product_obj.crafter != None:
                crafter_obj = product_obj.crafter.get()

            if crafter_obj != None:

                # Get other products by the crafter
                other_products_by_crafter = schema.Product.get_other_by_crafter(
                    product_obj.key, crafter_obj.key, limit=4)

                for product in other_products_by_crafter:
                    if product.image:
                        product.image_url = get_serving_url(product.image, 400)

                # Get the newest products
                newest_products = schema.Product.get_newest_for_homepage(
                    limit=15)

                for product in newest_products:
                    if product.image:
                        product.image_url = get_serving_url(product.image, 200)

                # Locales
                locales = {
                    "title": product_obj.name,
                    'product_obj': product_obj,
                    'other_products_by_crafter': other_products_by_crafter,
                    'newest_products': newest_products
                }

                # Render the template
                self.render('product.html', locales)

            else:

                # back to home !
                self.redirect('/')

        else:

            # Redirect to homepage
            self.redirect('/')
コード例 #25
0
ファイル: product.py プロジェクト: GDGCapeTown/CraftersOnline
	def get(self, product_id, product_name=False):

		product_obj = schema.Product.get_by_id( int(product_id) )

		if product_obj.image:
			product_obj.image_url = get_serving_url(product_obj.image, 500)
		
		if product_obj != None:

			if product_obj.image:
				product_image_url = get_serving_url(product_obj.image, 300)
				product_obj.image_url = product_image_url
			else:
				product_obj.image_url = "/img/product_300x300.jpg"

			if product_obj.crafter != None:
				crafter_obj = product_obj.crafter.get()

			if crafter_obj != None:

				# Get other products by the crafter
				other_products_by_crafter = schema.Product.get_other_by_crafter( product_obj.key, crafter_obj.key, limit=4 )

				for product in other_products_by_crafter:
					if product.image:
						product.image_url = get_serving_url(product.image, 400)

				# Get the newest products
				newest_products = schema.Product.get_newest_for_homepage(limit=15)

				for product in newest_products:
					if product.image:
						product.image_url = get_serving_url(product.image, 200)

				# Locales
				locales = {

					"title": product_obj.name,
					'product_obj': product_obj,
					'other_products_by_crafter': other_products_by_crafter,
					'newest_products': newest_products

				}

				# Render the template
				self.render('product.html', locales)

			else:

				# back to home !
				self.redirect('/')

		else:

			# Redirect to homepage
			self.redirect('/')
コード例 #26
0
ファイル: model.py プロジェクト: PreludeAndFugue/prelude-hmpc
 def data(self, size=211):
     '''Return information about photo and urls for image and thumb.'''
     title = self.title if self.title else 'Untitled'
     url = get_serving_url(self.blob, size=MAX_SIZE)
     thumb = get_serving_url(self.blob, size=size, crop=True)
     date = self.upload_date.strftime('%d %B, %Y')
     position = self.position if self.position is not None else ''
     score = self.total_score if position != '' else ''
     comp_title = self.competition.get().title
     return title, url, thumb, date, position, score, comp_title
コード例 #27
0
ファイル: profile_handler.py プロジェクト: ratana168/eventm
 def get(self, user_id=None):
   params = {}
   
   if user_id is not None  and len(user_id) > 1:
     user_info = self.user_model.get_by_id(long(user_id))
     upload_url = self.uri_for('edit-profile', user_id=user_id)            
     logger.debug('upload_url : ' + upload_url)
     if user_info.image:
       params['current_image'] = images.get_serving_url(user_info.image)
     if user_info.sport:
       params['sel_sport'] = [x.strip() for x in user_info.sport.split(',')]
     params['sports_list'] = constants.SPORTS_LIST
     params['media_upload_url'] = blobstore.create_upload_url(upload_url)      
     
     self.form = forms.UserProfileForm(self, user_info)
     return self.render_template('/cms/edit_profile.html', **params)
   
   '''logger.debug('User Id: ' + str(self.user_id))
   logger.debug('User Info: ' + str(self.user_info))
   logger.debug('User Type: ' + str(self.user_type))'''
   if self.user_info.image:
     params['current_image'] = images.get_serving_url(self.user_info.image)
   elif self.user_type[0] == 'facebook':
     params['current_image'] = 'https://graph.facebook.com/'+str(self.user_type[1])+'/picture?type=large'
   upload_url = self.uri_for('edit-user-image')
   params['media_upload_url'] = blobstore.create_upload_url(upload_url)
   upload_gallery_url = self.uri_for('upload-profile-gallery')
   params['upload_gallery_url'] = blobstore.create_upload_url(upload_gallery_url)
   params['title'] = self.user_info.name
   params['want_list'] = constants.WANT_DICT
   params['owner_info'] = self.user_info
   params['profile_gallery'] = self.mediaDao.get_all_media(self.user_info.key, constants.PROFILE)    
   params['owner_playgrounds'] = self.playgroundDao.query_by_owner(self.user_info)
   params['owner_events'] = self.eventDao.query_by_owner(self.user_info)    
   params['owner_trainingcentres'] = self.trainingcentreDao.query_by_owner(self.user_info)
   params['owner_teams'] = self.teamDao.query_by_owner(self.user_info, 'all', 4)
   
   recommend_events = self.eventDao.get_recommend(self.user_info.locality, self.user_info.sport, 4)
   params['recommend_events'] = recommend_events
   recommend_playgrounds = self.playgroundDao.get_recommend(self.user_info.locality, self.user_info.sport, 4)
   params['recommend_playgrounds'] = recommend_playgrounds    
   recommend_trainingcentres = self.trainingcentreDao.get_recommend(self.user_info.locality, self.user_info.sport, 4)
   params['recommend_trainingcentres'] = recommend_trainingcentres
       
   event_media = self.mediaDao.get_primary_media(recommend_events, constants.EVENT)
   params['event_media'] = event_media
   playground_media = self.mediaDao.get_primary_media(recommend_playgrounds, constants.PLAYGROUND)
   params['playground_media'] = playground_media
   trainingcentre_media = self.mediaDao.get_primary_media(recommend_trainingcentres, constants.TRAINING_CENTRE)
   params['trainingcentre_media'] = trainingcentre_media
   logger.debug(' event_media %s ' % len(event_media))
   logger.debug(' playground_media %s ' % len(playground_media))
   logger.debug(' trainingcentre_media %s ' % len(trainingcentre_media))
   
   return self.render_template('/cms/profile.html', **params)
コード例 #28
0
ファイル: __init__.py プロジェクト: andrewxhill/Commplish
    def post(self,pid):
        pk = db.Key.from_path('Project',pid.strip().lower())
        p = db.get(pk)

        sz = self.request.get('s', 64)

        try:
            assert int(sz) <= 256
        except:
            sz = 64

        age = datetime.datetime.now() - p.joinDate
        ageunit = 'days' if int(age.days) > 1 else 'day'
        memberct = len(UserModel.all(keys_only=True).filter('projects = ', pk).fetch(1000))
        memberct = str(memberct) if memberct < 1000 else "1000+"
        if p.icon:
            icon = images.get_serving_url(p.icon, size=256)
        else:
            icon = None

        out = {
                "pid": pid,
                "name": p.name,
                "fullName": p.fullName,
                "url": p.url,
                "about": p.about,
                "icon": icon,
                "age": "%s %s" % (str(age.days + 1), ageunit),
                "collections": [],
                "members": memberct,
              }
        """Add all the collections the project belongs to"""
        for bs in p.collections:
            bd = db.get(bs)
            if bd:
                s = {
                        "title": bd.title,
                        "about": bd.about,
                        "cid": self.toid(bd.title),
                        "badges": []
                    }
                """Add all the badges available"""
                for b in bd.badges:
                    t = {
                            "title": b.title,
                            "about": b.about,
                            "icon": images.get_serving_url(b.icon, size=int(sz)),
                            
                        }
                    s['badges'].append(t)
                out['collections'].append(s)

        self.response.out.write(
            simplejson.dumps(out)
        )
コード例 #29
0
ファイル: views.py プロジェクト: txm/make-good
def admin_bg_image(request):

    view_url = reverse('cms.views.admin_bg_image')

    if request.method == 'POST':

        form = BackgroundImageForm(request.POST, request.FILES)

        if form.is_valid():

            user = users.get_current_user()

            bg_image_form = form.save(commit=False)
            bg_image_form.author = user
            bg_image_form.file_name = request.FILES['image']
            bg_image_form.save()

            #bg_image_form.content_type = ('image/' + (str(request.FILES['image'])).partition('.')[2]).lower

            bg_image = BackgroundImage.objects.get(id=bg_image_form.id)
            blob_key = bg_image.image.file.blobstore_info.key()._BlobKey__blob_key 
            img = images.Image(blob_key=blob_key)
            bg_image.blob_key = blob_key
            bg_image.url = images.get_serving_url(blob_key)
            bg_image.url_thumb = images.get_serving_url(blob_key, 200)
            bg_image.save()

            #bg_image = BackgroundImage.objects.get(id=bg_image_form.id)

            #file_name = files.blobstore.create(mime_type='application/octet-stream')
            #with files.open(file_name, 'a') as f:
            #    f.write(bg_image.image)
            #files.finalize(file_name)
            #blob_key = files.blobstore.get_blob_key(file_name)

            #bg_image.thumb_content_type = ('image/png').lower

            #bg_image.save()

            return HttpResponseRedirect('/admin/bg_image?message=' + 'Updated')

    else:
        form = BackgroundImageForm()

    upload_url, upload_data = prepare_upload(request, view_url)
    form = BackgroundImageForm()
    #bg_images = BackgroundImage.objects.all().values('id', 'title', 'author', 'file_name', 'content_type', 'date_inserted' )
    bg_images = BackgroundImage.objects.all().values()

    return render_to_response('admin_bg_image.html', {
        'form': form, 
        'bg_images': bg_images,
        'upload_url': upload_url, 
        'upload_data': upload_data,
    }, context_instance=RequestContext(request))
コード例 #30
0
ファイル: views.py プロジェクト: Rivinek/Auction-Comparer
    def post(self):
        """Post function"""
        user_name = users.get_current_user() and users.get_current_user()\
            .nickname() or 'anonymous'
        sended = Searched(parent=user_key(user_name))

        if users.get_current_user():
            sended.author = users.get_current_user()

        keyword = cgi.escape(self.request.get('keyword'))
        keyword = keyword.split()[0]

        allegro_price = allegro_api(keyword)[0]
        nokaut_price = nokaut_api(
            keyword, 'a8839b1180ea00fa1cf7c6b74ca01bb5')[0]
        allegro_url = allegro_api(keyword)[1]
        nokaut_url = nokaut_api(
            keyword, 'a8839b1180ea00fa1cf7c6b74ca01bb5')[1]
        allegro_image_url = allegro_api(keyword)[2]
        nokaut_image_url = nokaut_api(
            keyword, 'a8839b1180ea00fa1cf7c6b74ca01bb5')[2]

        if allegro_price < nokaut_price:
            url = allegro_url
        else:
            url = nokaut_url

        blob_key_allegro = make_blob_key(allegro_image_url)
        blob_key_nokaut = make_blob_key(nokaut_image_url)
        img_nokaut = images.get_serving_url(blob_key_nokaut)
        img_allegro = images.get_serving_url(blob_key_allegro)
        img_mini_allegro = "".join([img_allegro, "=s100"])
        img_mini_nokaut = "".join([img_nokaut, "=s100"])

        sended.blob_allegro = blob_key_allegro
        sended.blob_nokaut = blob_key_nokaut
        sended.url = url
        sended.content = keyword
        sended.put()

        template_values = {
            "allegro_url": allegro_url,
            "allegro_price": allegro_price,
            "nokaut_url": nokaut_url,
            "nokaut_price": nokaut_price,
            "prod_name": cgi.escape(self.request.get('content')),
            "img_nokaut": img_nokaut,
            "img_allegro": img_allegro,
            "img_mini_allegro": img_mini_allegro,
            "img_mini_nokaut": img_mini_nokaut
        }
        self.render_template(
            'templates/resoult.html', template_values=template_values
        )
コード例 #31
0
ファイル: models.py プロジェクト: goyalankit/imgshare
 def __dict__(self, resize=None):
     if resize:
         url = images.get_serving_url(self.blob_key) + ('=s%s' % resize)
     return {
             "id" : self.key().id(),
             "url" : images.get_serving_url(self.blob_key),
             "comments" : self.comments,
             "stream_id" : self.stream.key().id(),
             "location" : self.location or (random.random()*180 - 90, random.random()*360 - 180),
             "created_at" :  self.created_at.strftime("%Y-%m-%d")
             }
コード例 #32
0
  def get(self,resource):
	self.response.out.write("<html><head><script>function goBack() {window.history.back()} </script></head><body>")
	#For showing images followed by a Link
	# self.response.out.write("<a href='%s'>Origonal Size</a> <br><a href='%s'>Object in 150 Size(for Images)</a><br> <a href='%s'>Object in 80 Size(for Images)</a><br><br><button onclick='goBack()'>Upload Another File</button> " % (images.get_serving_url(resource),
	# images.get_serving_url(resource, 150),
	# images.get_serving_url(resource, 80)))
	
	#For showing images directly use the code below
	self.response.out.write("<b>Origonal Size   :   </b>  <img src='%s' alt='Origonal Size'> <br><b>Object in 150 Size(for Images)   :   </b>  <img src='%s' alt='Object in 150 Size(for Images)'><br><br> <b>Object in 80 Size(for Images)   :   </b>  <img src='%s' alt='Object in 80 Size(for Images)'><br><br><button onclick='goBack()'>Upload Another File</button> " % (images.get_serving_url(resource),
	images.get_serving_url(resource, 150),
	images.get_serving_url(resource, 80)))
	self.response.out.write("</html></body>")
コード例 #33
0
 def get_photo(self,
               key,
               published_filter=True,
               src_width=settings.photo_s_w,
               src_height=settings.photo_s_h):
     if key:
         try:
             photo = Photo.get(key)
             if (published_filter
                     and photo.published) or not published_filter:
                 self.templateapi.manipulator.formater(
                     photo, [{
                         'name': 'description',
                         'type': 'unicode'
                     }])
                 if settings.photo_get_serving_url:
                     if src_width > src_height:
                         src_size = src_width
                     else:
                         src_size = src_height
                     photo.src = images.get_serving_url(
                         photo.photo.key(), src_size)
                     photo.view_url = images.get_serving_url(
                         photo.photo.key(), settings.photo_l)
                 else:
                     photo.src = self.templateapi.get_redirect(
                         settings.photo_output_url_string %
                         str(photo.photo.key()), 'add_multi',
                         [{
                             'query': 'width',
                             'value': src_width
                         }, {
                             'query': 'height',
                             'value': src_height
                         }])
                     photo.view_url = self.templateapi.get_redirect(
                         settings.photo_output_url_string %
                         str(photo.photo.key()), 'add_multi',
                         [{
                             'query': 'width',
                             'value': settings.photo_l_w
                         }, {
                             'query': 'height',
                             'value': settings.photo_l_h
                         }])
                 photo.like_url = self.templateapi.get_redirect(
                     settings.photo_view_url_string % str(photo.key().id()))
                 return photo
             else:
                 return None
         except:
             return None
     return None
コード例 #34
0
ファイル: handlers.py プロジェクト: Gembok/Tripin-website
 def article(self, id):
     if not id:
         item = self.m.all().get()
     else:
         item = self.m.get_by_id(id)
     if not item:
         return False
     itemd = utils.to_dict(item)
     key = itemd['img']
     itemd['img'] = images.get_serving_url(key, 200)
     itemd['img_big'] = images.get_serving_url(key, 1024)
     return itemd
コード例 #35
0
ファイル: views.py プロジェクト: txm/make-good
def admin_bg_image_edit(request, bg_image_id=None):

    view_url = reverse('cms.views.admin_bg_image') #.'+bg_image_id)
    view_url = view_url + 'edit/' + str(bg_image_id) # FFS!

    if request.method == 'POST':

        bg_image = BackgroundImage.objects.get(id=bg_image_id)
        form = BackgroundImageForm(instance=bg_image, data=request.POST, files=request.FILES)

        if form.is_valid():

            user = users.get_current_user()

            bg_image_form = form.save(commit=False)
            bg_image_form.author = user

            if 'image' in request.FILES: #and request.FILES['image'] is True:
                bg_image_form.file_name = request.FILES['image']

            bg_image_form.save()

            bg_image = BackgroundImage.objects.get(id=bg_image_form.id)

            blob_key = bg_image.image.file.blobstore_info.key()._BlobKey__blob_key
            img = images.Image(blob_key=blob_key)
            bg_image.blob_key = blob_key
            bg_image.url = images.get_serving_url(blob_key)
            bg_image.url_thumb = images.get_serving_url(blob_key, 200)

            bg_image.save()

            key = 'bg_image_serve' + '-' + str(bg_image.id)
####            memcache.delete(key)

            ## TODO memcache.add() here
            ## Noel 07828 510 920

            return HttpResponseRedirect('/admin/bg_image/?message=' + urllib.quote_plus('Image has been updated') )

    else:

        bg_image = BackgroundImage.objects.get(id=bg_image_id)
        form = BackgroundImageForm(instance=bg_image)

        upload_url, upload_data = prepare_upload(request, view_url)

        return render_to_response('admin_bg_image_edit.html', {
            'form': form, 
            'bg_image': bg_image,
            'upload_url': upload_url, 
            'upload_data': upload_data,
        }, context_instance=RequestContext(request))
コード例 #36
0
ファイル: ViewStream.py プロジェクト: ttillett13/GrayTeam
    def build_template(current_user, request, page_size):
        stream_name = request.get('stream_name')
        status = request.get('status')
        page = request.get('page')

        # TODO: For some reason stream = Stream.query(Stream.name == stream_name).get() does not work... fix it later
        for i in Stream.query().fetch():
            if i.name == stream_name:
                stream = i

        time = datetime.datetime.time(datetime.datetime.now())
        stream.view_times.append(time)
        stream.times_viewed = stream.times_viewed + 1
        stream.put()

        pics = []
        if stream.pictures:
            if not page:
                page = len(stream.pictures)
            page = int(page)
            if page == 0:
                page = len(stream.pictures)
            if page_size == 3:  # web app
                iter = 0
                for i in reversed(range(page - page_size, page)):
                    if iter < len(stream.pictures):
                        pic_temp = stream.pictures[i].get()
                        pics.append((pic_temp.name,
                                     images.get_serving_url(pic_temp.image,
                                                            secure_url=False)))
                    iter += 1
            else:
                for picture in stream.pictures:
                    pic = picture.get()
                    pics.append((pic.name,
                                 images.get_serving_url(pic.image,
                                                        secure_url=False),
                                 pic.date_uploaded))
                #pictures = sorted(pictures, key=lambda x: x[4])
                pics = sorted(pics, key=lambda x: x[2], reverse=True)
        else:
            page = 0

        template_values = {
            'stream': stream,
            'pics': pics,
            'status': status,
            'page': page,
            'stream_name': stream.name
        }

        return template_values
コード例 #37
0
ファイル: recipe_box.py プロジェクト: liuhsinyu/APT_Foodbook
    def get(self):
        user_id = self.session.get('user_id')
        print user_id
        print 'ooooooooooooo'
        save_cache = Save_cache.get_by_id(DEFAULT_Save_Cache_NAME)
        if not save_cache:
            save_cache = Save_cache(id=DEFAULT_Save_Cache_NAME)
        user = User.get_by_id(user_id)
        my_recipes_list = []
        recipe_query = Recipe.query(Recipe.author == user_id)
        my_recipes = recipe_query.fetch()
        for recipe in my_recipes:
            print recipe
            recipe_dict = {'photo':'http://placehold.it/700x400',
                           'name':recipe.name,
                           'tags':recipe.tags,
                           'id':str(recipe.key.id()),
                           }
            if len(recipe.photos)>0:
                recipe_dict['photo'] = images.get_serving_url(recipe.photos[0].blob_key)
            my_recipes_list.append(recipe_dict)

        favorite_recipes_list = []
        for recipe_id in user.favorite_recipes:
            recipe = Recipe.get_by_id(long(recipe_id))
            recipe_dict = {'photo':'http://placehold.it/700x400',
                           'name':recipe.name,
                           'tags':recipe.tags,
                           'id':str(recipe.key.id()),
                           }
            if len(recipe.photos)>0:
                recipe_dict['photo'] = images.get_serving_url(recipe.photos[0].blob_key)
            favorite_recipes_list.append(recipe_dict)
        wish_recipes_list = []
        for recipe_id in user.wish_recipes:
            recipe = Recipe.get_by_id(long(recipe_id))
            recipe_dict = {'photo':'http://placehold.it/700x400',
                           'name':recipe.name,
                           'tags':recipe.tags,
                           'id':str(recipe.key.id()),
                           }
            if len(recipe.photos)>0:
                recipe_dict['photo'] = images.get_serving_url(recipe.photos[0].blob_key)
            wish_recipes_list.append(recipe_dict)
        template = JINJA_ENVIRONMENT.get_template('template/recipebox_page.html')
        template_values = {
            'my_recipes':my_recipes_list,
            'favorite_recipes':favorite_recipes_list,
            'wish_recipes':wish_recipes_list,
            'keywords':json.dumps(save_cache.save_cache),
        }
        self.response.write(template.render(template_values))
コード例 #38
0
ファイル: main.py プロジェクト: Kulikovpavel/IstraHistory
    def post(self):
        upload_files = self.get_uploads('file')  # 'file' is file upload field in the form

#        image_type = imghdr.what(upload_files[0].filename)
#        if not image_type:
#            self.redirect('/')
        title = self.request.get('title').replace('\\', '')
        description = self.request.get('description').replace('\\', '')
        source = self.request.get('source').replace('\\', '')

        logging.debug(self.request)
        try:
            year = int(self.request.get('year'))
        except:
            year = 1945
        tags = list(self.request.get('tags').lower().replace('\\', '').replace("'", '').split(','))  # теги в нижний регистр, разделяем по запятой и в лист

        coordinates = self.request.get('coordinates')
        direction = self.request.get('direction')
        if not coordinates:
            coordinates = '55.914125,36.860562' # center of Istra if no coords
        if direction:
            direction = int(direction)
        else:
            direction = 9

        if upload_files and self.user:
            blob_info = upload_files[0]
            key = blob_info.key()
#            print tags
            picture = Picture(blob_key = key ,
                              link = images.get_serving_url(key, size=0),
                              thumb = images.get_serving_url(key, size=75),
                              user = self.user,
                              title = title,
                              description = description,
                              source = source,
                              year = year,
                              tags = tags,
                              coordinates = coordinates,
                              direction = direction,
                              parent=main_key())
            picture.put()
            memcache.set('picture_' + str(picture.key().id()),picture)
            self.tags_update(tags)
            self.pictures_update()

            # self.redirect(images.get_serving_url(key))
            # self.redirect('/serve/%s' %key )
            self.redirect('/')
        else:
            self.redirect('/')
コード例 #39
0
ファイル: main.py プロジェクト: Murice-D-Miller/podato-images
 def get(self, size):
     url = self.request.get("url")
     key = memcache.get(url)
     if not key:
         key = fetch_and_store(url)
         memcache.set(url, key)
     try:
         img_url = images.get_serving_url(key, secure_url=True, size=int(size))
     except images.ObjectNotFoundError:
         key = fetch_and_store(url)
         memcache.set(url, key)
         img_url = images.get_serving_url(key, secure_url=True)
     self.redirect(img_url, permanent=True)
コード例 #40
0
 def to_dict(self, include=None, exclude=None):
     """calls the super method, and add a URL
     :param include: set of property names to include, default all
     :param exclude: set of property names to exclude, default none
     :param size: the size of the image. default None (original size)
     :return:
     """
     d = super(Image, self).to_dict(include=include, exclude=exclude)
     d['id'] = self.key.id()
     d['small_url'] = get_serving_url(self.small_blob_key, 180)
     d['large_url'] = get_serving_url(self.large_blob_key, 738)
     return d
     pass
コード例 #41
0
ファイル: woof.py プロジェクト: abhiklodh/open-hub
 def to_dict(self):
     url = images.get_serving_url(self.data.key())
     thumbnail_size = IMG_SERVING_CROP_SIZES[5]; # = 104
     thumbnail_url = images.get_serving_url(self.data.key(), size = thumbnail_size, crop = True) 
     return {
             'height':self.height,
             'width':self.width,
             'url':url,
             'thumbnails':[{
                             'url':thumbnail_url, 
                             'width':thumbnail_size, 
                             'height':thumbnail_size}],
             }
コード例 #42
0
ファイル: profile_handler.py プロジェクト: ratana168/eventm
 def post(self):    
   upload_files = self.get_uploads('file')
   id = self.request.get("user_id")    
   user = User.get_by_id(long(id))
   redirect_url = self.uri_for('profile')    
   if upload_files is not None and len(upload_files) > 0:
     blob_info = upload_files[0]
     user.image = blob_info.key()
     user.image_url = images.get_serving_url(blob_info.key())
     user.put()
     logger.info('Link to image ' + images.get_serving_url(user.image))
   
   #return json.dumps(result) #or, as it is an empty json, you can simply use return "{}"
   return self.redirect(redirect_url)
コード例 #43
0
    def get(self):
        designs = db.GqlQuery("SELECT * FROM Design ORDER BY created DESC")
        #design_query = Design.all()
        #designs = design_query.fetch(10)

        imageUrls = {
            design.key():
            [(images.get_serving_url(design.imageBlobs[0]) + '=s453'),
             (images.get_serving_url(design.imageBlobs[3]) + '=s453'),
             (images.get_serving_url(design.imageBlobs[6]) + '=s453'),
             images.get_serving_url(design.imageBlobCommon)]
            for design in designs
        }
        self.render("front.htm", designs=designs, imageUrls=imageUrls)
コード例 #44
0
    def _get_urls_for(self, file_name):
        user = users.get_current_user()
        if user is None:
            return

        bucket_name = app_identity.get_default_gcs_bucket_name()
        path = os.path.join('/', bucket_name, user.user_id(), file_name)
        real_path = '/gs' + path
        key = blobstore.create_gs_key(real_path)
        try:
            url = images.get_serving_url(key, size=0)
            thumbnail_url = images.get_serving_url(key, size=150, crop=True)
        except images.TransformationError, images.NotImageError:
            url = "http://storage.googleapis.com{}".format(path)
            thumbnail_url = None
コード例 #45
0
    def get(self):
        stream_name = self.request.get("name")
        stream = Stream.query(
            Stream.name == stream_name,
            ancestor=streambook_key()) \
            .fetch()
        if stream:
            stream = stream[0]

        imgs = Photo.query(
            ancestor=stream.key) \
            .order(-Photo.date) \
            .fetch()

        stream.num_of_views += 1
        stream.view_dates.append(datetime.datetime.now())
        stream.put()

        img_urls = [images.get_serving_url(img.img_key) for img in imgs]
        img_caps = [img.name for img in imgs]

        data = {
            'ImageList': img_urls,
            'ImageCaptionList': img_caps,
            'UserEmail': stream.author.email
        }
        json_data = json.dumps(data)

        self.response.write(json_data)
コード例 #46
0
ファイル: models.py プロジェクト: dargonar/DirectoDueno
    def put(self):
        if self.email and len(self.email):
            blob_key = render_text_into_blob(self.email)
            self.email_image = blob_key
            self.email_image_url = get_serving_url(blob_key)

        super(RealEstate, self).put()
コード例 #47
0
def upload_image_to_bucket(file_obj, bucket_path):
    """upload file to bucket.

    The retry_params specified in the open call will override the default
    retry params for this particular file handle.

    Arguments:
      file_obj: file object
      bucket_path: file name
      
    Return:
      str: image serving url
      str: bucket key  
  """
    logging.info('uploading_file_to_bucket %s\n' % bucket_path)
    content_type = mimetypes.guess_type(bucket_path)[0]

    if not content_type:
        logging.warning('Mimetype not guessed for: %s', bucket_path)

    write_retry_params = gcs.RetryParams(backoff_factor=1.1)
    try:
        with gcs.open(bucket_path,
                      'w',
                      content_type=content_type,
                      options={b'x-goog-acl': b'public-read'}) as f:
            f.write(file_obj)
            bucket_key = blobstore.create_gs_key('/gs' + bucket_path)
            serving_url = images.get_serving_url(bucket_key)
        return serving_url, bucket_key
    except Exception, e:
        logging.error(
            'Blob write failed for %s, exception: %s. Additional info was logged'
            % (bucket_path, str(e)))
コード例 #48
0
def store_image_to_blobstore(imgurl):
    if not imgurl:
        return False
    
    # retry 3 times max
    for i in range(0,3):
        try:
            # img is google.appengine.ext.blobstore.blobstore.BlobInfo object
            img, blob_key, width, height = core.url_upload(imgurl, imgurl)
            logging.info('core.url_upload success!')
            # if fetch success, jump out forloop(to prevent from urlfetch fail)
            break
        except:
            logging.info('core.url_upload fail!')
            img, blob_key, width, height = core.url_upload(imgurl, imgurl)

    # get picasa url
    result = images.get_serving_url(img)

    logging.info('img width: %s, img height: %s' % (width, height))

    # convert width and height from float(possible) to int
    width = int(width)
    height = int(height)

    if width > height:
        result = result + '=s' + str(width)
    else:
        result = result + '=s' + str(height)

    logging.info("New imgurl: %s" % result)

    return result, blob_key, width, height
コード例 #49
0
 def handle_upload(self):
     results = []
     blob_keys = []
     for name, fieldStorage in self.request.POST.items():
         if type(fieldStorage) is unicode:
             continue
         result = {}
         result['name'] = re.sub(r'^.*\\', '', fieldStorage.filename)
         result['type'] = fieldStorage.type
         result['size'] = self.get_file_size(fieldStorage.file)
         if self.validate(result):
             blob_key = str(self.write_blob(fieldStorage.value, result))
             blob_keys.append(blob_key)
             result['deleteType'] = 'DELETE'
             result['deleteUrl'] = self.request.host_url +\
                 '/?key=' + urllib.quote(blob_key, '')
             if (IMAGE_TYPES.match(result['type'])):
                 try:
                     result['url'] = images.get_serving_url(
                         blob_key,
                         secure_url=self.request.host_url.startswith(
                             'https'))
                     result['thumbnailUrl'] = result['url'] +\
                         THUMBNAIL_MODIFICATOR
                 except:  # Could not get an image serving url
                     pass
             if not 'url' in result:
                 result['url'] = self.request.host_url +\
                     '/' + blob_key + '/' + urllib.quote(
                         result['name'].encode('utf-8'), '')
         results.append(result)
     deferred.defer(cleanup, blob_keys, _countdown=EXPIRATION_TIME)
     return results
コード例 #50
0
ファイル: storages.py プロジェクト: salvadormrf/django-gaekit
 def url(self, filename):
     if not is_hosted():
         key = blobstore.create_gs_key('/gs' + self._real_path(filename))
         return images.get_serving_url(key)
     return 'https://storage.googleapis.com{path}'.format(
         path=self._real_path(filename)
     )
コード例 #51
0
    def upload_image(self, blob, filename):
        mime_type = 'image/png'
        if filename.split('.')[-1] == 'jpg' or filename.split(
                '.')[-1] == 'jpeg':
            mime_type = 'image/jpeg'

        bucket_name = os.environ.get(
            'BUCKET_NAME', app_identity.get_default_gcs_bucket_name())
        bucket = '/' + bucket_name
        filename_final = bucket + '/' + str(uuid.uuid4())

        # Create a GCS file with GCS client.
        with gcs.open(filename_final, 'w') as f:
            f.write(blob)
            f.close()

        # Blobstore API requires extra /gs to distinguish against blobstore files.
        blobstore_filename = '/gs' + filename_final

        # Get the file's blob key
        blob_key = blobstore.create_gs_key(blobstore_filename)
        # Store it
        self.image = blob_key
        self.mime_type = mime_type
        self.url = get_serving_url(blob_key)
コード例 #52
0
    def post(self):
        if self.request.get('imagestore_key'):
            image = dbImageStore.ImageStore.get(
                self.request.get('imagestore_key'))
        else:
            image = dbImageStore.ImageStore()

        image.name = self.request.get('image_name')
        image.imageReferance = self.request.get('image_referance')

        upload_files = self.get_uploads('image_file')

        if upload_files:
            image.imageUrl = images.get_serving_url(str(upload_files[0].key()))

        imageKey = db.put(image)

        for market in Settings.markets:
            language = market['language']
            description = self.request.get('image_description_' + language)
            if description:
                imageDescription = dbImageStore.ImageDescription.gql(
                    'WHERE imageEntry = :imageEntry AND lang = :lang',
                    imageEntry=imageKey,
                    lang=language).get()
                if imageDescription is None:
                    imageDescription = dbImageStore.ImageDescription()
                    imageDescription.imageEntry = imageKey
                    imageDescription.lang = language

                imageDescription.description = description
                db.put(imageDescription)

        self.redirect('/edit/ImageStore/?status=1&message=Image added/updated')
コード例 #53
0
    def getGeoViewImageInfo(self):
        stream_key = self.getStreamKey()

        images_info = []
        currentTime = datetime.now()
        aYearAgo = currentTime - timedelta(days=365)

        image_query = common.Image.query(common.Image.stream_key == stream_key).order(-common.Image.upload_date)
        image_list = image_query.fetch()

        for image in image_list:
            createTime = str(image.upload_date)[:10] + 'T' + str(image.upload_date)[11:] + 'Z'
            # date_object = datetime.strptime(createTime, '%Y-%m-%d')

            lat = - 57.32652122521709 + 114.65304245043419 * random.random()
            lon = - 123.046875 + 246.09375 * random.random()

            # if aYearAgo <= date_object:
            images_info.append({
                "url": images.get_serving_url(image.blob_key),
                "lon": lon,
                "lat": lat,
                "createTime": createTime
            })

        return images_info
コード例 #54
0
 def get(self, team_id=None):
   params = {}
   
   import_url = self.uri_for('import-team')
   params['import_url'] = blobstore.create_upload_url(import_url)
   upload_url = self.uri_for('create-team')
   continue_url = self.request.get('continue').encode('ascii', 'ignore')
   params['continue_url'] = continue_url
   #params['continue_url'] = continue_url if continue_url != '' else upload_url    
   #params['players'] = self.playerDao.query_by_owner(self.user_info)
   params['players'] = self.profileDao.query_by_all(self.user_info)
   params['title'] = 'Create New Team'
   
   if team_id is not None  and len(team_id) > 1:
     upload_url = self.uri_for('edit-team', team_id = team_id)
     team = self.teamDao.get_record(team_id)
     params['title'] = 'Update - ' + str(team.name)
     if team.logo:
       params['current_logo'] = images.get_serving_url(team.logo)
     self.form = forms.TeamForm(self, team)
     players = []
     for x in xrange(len(team.players)):
       players.append(team.players[x].id())
     params['sel_players'] = players
     params['media_upload_url'] = blobstore.create_upload_url(upload_url)
     return self.render_template('/cms/create_team.html', **params)
   else:
     params['media_upload_url'] = blobstore.create_upload_url(upload_url)
     return self.render_template('/cms/create_team.html', **params)        
   
   params['entity_name'] = 'Team'
   params['owner_teams'] = self.teamDao.query_by_owner(self.user_info)
   return self.render_template('/cms/dashboard.html', **params)
コード例 #55
0
ファイル: album.py プロジェクト: jgresham/photo-gallery
def resource_db_from_upload(album_db):
    try:
        uploaded_file = flask.request.files['file']
    except:
        return None
    headers = uploaded_file.headers['Content-Type']
    blob_info_key = werkzeug.parse_options_header(headers)[1]['blob-key']
    blob_info = blobstore.BlobInfo.get(blob_info_key)

    image_url = None
    if blob_info.content_type.startswith('image'):
        try:
            image_url = images.get_serving_url(blob_info.key())
        except:
            pass

    resource_db = model.Resource(
        album_key=album_db.key,
        user_key=auth.current_user_key(),
        blob_key=blob_info.key(),
        name=blob_info.filename,
        content_type=blob_info.content_type,
        size=blob_info.size,
        image_url=image_url,
        bucket_name=config.CONFIG_DB.bucket_name or None,
    )
    resource_db.put()
    return resource_db
コード例 #56
0
 def post(self):    
   upload_files = self.get_uploads('file')
   id = self.request.get("team_id")    
   team = Team.get_by_id(long(id))
   logger.debug('team detail : ' + str(team))
   logger.debug('upload_files : ' + str(upload_files))
   redirect_url = self.uri_for('view-team', team_id=id)
   if upload_files is not None and len(upload_files) > 0:
     blob_info = upload_files[0]
     team.logo = blob_info.key()
     team.logo_url = images.get_serving_url(blob_info.key())
     team.put()
     logger.info('Link to image ' + images.get_serving_url(team.logo))
   
   #return json.dumps(result) #or, as it is an empty json, you can simply use return "{}"
   return self.redirect(redirect_url)
コード例 #57
0
ファイル: main.py プロジェクト: grow/grow-ext-file-upload
 def post(self):
     file_id = self.request.POST.get('file_id')
     key = ndb.Key('UploadedFile', file_id)
     ent = key.get()
     if ent.gs_path.endswith(IMAGE_EXTENSIONS):
         blob_key = blobstore.create_gs_key('/gs{}'.format(ent.gs_path))
         serving_url = images.get_serving_url(blob_key, secure_url=True)
         data = blobstore.fetch_data(blob_key, 0, 50000)
         image = images.Image(image_data=data)
         ent.width = image.width
         ent.height = image.height
     else:
         serving_url = 'https://storage.googleapis.com{}'.format(
             ent.gs_path)
         ent.width = 0
         ent.height = 0
     ent.serving_url = serving_url
     ent.put()
     self.json_response({
         'file_id': file_id,
         'gs_path': ent.gs_path,
         'serving_url': serving_url,
         'width': ent.width,
         'height': ent.height,
     })
コード例 #58
0
def save_file(binary,
              filename,
              public=True,
              mime_type="application/octet-stream"):
    from google.appengine.api import files

    today = datetime.now().strftime("%Y_%m_%d_")
    filename = today + filename

    blob_file_name = files.blobstore.create(
        _blobinfo_uploaded_filename=filename)
    with files.open(blob_file_name, 'a') as f:
        f.write(binary)
    files.finalize(blob_file_name)
    blob_key = files.blobstore.get_blob_key(blob_file_name)

    try:
        # get serving url for images
        from google.appengine.api import images
        img = images.Image(binary)
        size = max(img.width, img.height)
        url = images.get_serving_url(blob_key, size=size)
    except:
        from settings import BLOB_SERVING_URL
        url = "%s/%s" % (BLOB_SERVING_URL, str(blob_key))

    return url, str(blob_key)
コード例 #59
0
 def save(self, force_insert=False, force_update=False, using=None):
     """
     saves the serving url so we never need an rpc to generate it.
     """
     self.serving_url = images.get_serving_url(self._get_blobstore_key())
     return super(BaseImageModel, self).save(force_insert, force_update,
                                             using)