Example #1
0
def transfer_s3_structure_to_db(name, path, parent_directory, is_dir=False):
    if parent_directory is not None:
        par_dir = Directory.get(Directory.key == parent_directory)
    else:
        par_dir = FakeDirectory()
        par_dir.id = None
    if is_dir:
        try:
            Directory.get(Directory.key == path)
            return False
        except DoesNotExist:
            Directory.create(
                name = name,
                key = path,
                parent_directory = par_dir.id
            )
            return True
    else:
        try:
            Image.get(Image.key == path)
            return False
        except DoesNotExist:
            Image.create(
                name = name,
                key = path,
                directory = par_dir.id
            )
            return True
Example #2
0
def get_image(id):
    # Get image #id
    try:
        image = Image.get(Image.id == id)
    except Image.DoesNotExist:
        return jsonify(**IMAGE_NOT_FOUND)

    return render_template("image.html", image=image)
Example #3
0
def get_image(id):
    # Get image #id
    try:
        image = Image.get(Image.id == id)
    except Image.DoesNotExist:
        return jsonify(**IMAGE_NOT_FOUND)

    return render_template("image.html", image=image)
Example #4
0
    def get(self):
        item = None
        if self.request.get('key'):
            item = Image.get( self.request.get('key') )

        vals = {
            'item'       : item,
            # this is either new.html or edit.html
            'upload_url' : blobstore.create_upload_url( str(urllib.unquote(self.request.path)) ),
            }
        self.template( 'image-form.html', vals, 'admin' );
Example #5
0
 def post(self,key):
     try:
         image = Image.get(Key(key))
         post = self.request.POST
         image.name=post['name']
         image.title=post['title']
         image.alt=post['alt']
         image.put()
         self.render_template('editImage',{'image':image})
     except BadKeyError:
         self.render_template('editImage',{'error':"Image Not Found"})
Example #6
0
 def post(self):
     if not self.has_permission:
         return
     user = self.current_user
     content = self.get_argument('content', None)
     image_ids = self.get_argument('image_ids', None)
     images = []
     if content and len(strip_tags(content)) >= 3:
         tweet = Tweet(content=strip_xss_tags(content), user_id=user.id).save()
         tweet.put_notifier()
         if image_ids:
             image_ids = image_ids.split(',')
             for image_id in image_ids:
                 image_id = int(image_id)
                 image = Image.get(id=image_id)
                 if image:
                     image.tweet_id = tweet.id
                     images.append({
                         'id': image.id,
                         'path': image.path,
                         'width': image.width,
                         'height': image.height,
                         })
         if images != []:
             tweet.has_img = 'true'
         result = {
                     'status'          : 'success',
                     'message'         : '推文创建成功',
                     'content'         : tweet.content,
                     'name'            : tweet.author.name,
                     'nickname'        : tweet.author.nickname,
                     'author_avatar'   : tweet.author.get_avatar(size=48),
                     'author_url'      : tweet.author.url,
                     'author_name'     : tweet.author.name,
                     'author_nickname' : tweet.author.nickname,
                     'tweet_url'       : tweet.url,
                     'created'         : tweet.created,
                     'id'              : tweet.id,
                     'images'          : images,
                 }
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect('/timeline')
     result = {
                 'status': 'error',
                 'message': '推文内容至少 3 字符'
             }
     if self.is_ajax:
         return self.write(result)
     self.flash_message(result)
     return self.redirect('/timeline')
Example #7
0
    def get(self):
        try:
            if self.request.get('key'):
                item = Image.get( self.request.get('key') )

                vals = {
                    'item' : item,
                    }
                self.template( 'image-del.html', vals, 'admin' );
            else:
                self.redirect('.')
        except:
            self.redirect('.')
Example #8
0
    def post(self, image_key):
        """<input type="hidden" name="crop[x]" value="0" />
		<input type="hidden" name="crop[y]" value="0" />
		<input type="hidden" name="crop[w]" value="0" />
		<input type="hidden" name="crop[h]" value="0" />"""

        left = float(self.request.POST["crop[x]"])
        top = float(self.request.POST["crop[y]"])
        right = float(self.request.POST["crop[w]"])
        bottom = float(self.request.POST["crop[h]"])

        img = Image.get(image_key)
        img.do_crop(left, top, right, bottom)

        self.redirect("/%s/crop/%s" % (IMAGE_APP_PATH, str(img.key())))
Example #9
0
def delete_image(id):
    # Get image #id
    try:
        image = Image.get(Image.id == id)
    except Image.DoesNotExist:
        return jsonify(**IMAGE_NOT_FOUND)

    # TODO: Delete image binary file and thumb
    # Need to check safe path and MIME type first

    # Delete image DB record
    query = Image.delete().where(Image.id == id)
    query.execute()

    # return JSON status OK
    return jsonify(**STATUS_OK)
Example #10
0
 def put(self, image_id):
     image_id = int(image_id)
     image = Image.get(id=image_id)
     if not image:
         raise tornado.web.HTTPError(404)
     album_id = self.get_int('album_id', None)
     if not album_id:
         return self.send_error_result(msg=u'没有指定专辑哦')
     album = Album.get(id=album_id)
     if not album:
         return self.send_error_result(msg=u'专辑不存在')
     if album.user_id != self.current_user.id:
         return self.send_error_result(msg=u'此专辑不是您的专辑')
     if image.album_id != album_id:
         image.album_id = album_id
     return self.send_success_result()
Example #11
0
 def put(self, image_id):
     image_id = int(image_id)
     image = Image.get(id=image_id)
     if not image:
         raise tornado.web.HTTPError(404)
     album_id = self.get_int('album_id', None)
     if not album_id:
         return self.send_error_result(msg=u'没有指定专辑哦')
     album = Album.get(id=album_id)
     if not album:
         return self.send_error_result(msg=u'专辑不存在')
     if album.user_id != self.current_user.id:
         return self.send_error_result(msg=u'此专辑不是您的专辑')
     if image.album_id != album_id:
         image.album_id = album_id
     return self.send_success_result()
Example #12
0
def delete_image(id):
    # Get image #id
    try:
        image = Image.get(Image.id == id)
    except Image.DoesNotExist:
        return jsonify(**IMAGE_NOT_FOUND)

    # TODO: Delete image binary file and thumb
    # Need to check safe path and MIME type first

    # Delete image DB record
    query = Image.delete().where(Image.id == id)
    query.execute()

    # return JSON status OK
    return jsonify(**STATUS_OK)
Example #13
0
 def post(self):
     try:
         item = Image.get( self.request.get('key') ) if self.request.get('key') else None
         if item is not None:
             try:
                 if item.blob:
                     item.blob.delete()
                 item.delete()
                 self.redirect('.')
             except:
                 vals = {
                     'item' : item,
                     'err' : 'There was an error when deleting this image, please try again'
                     }
                 self.template( 'image-del.html', vals, 'admin' );
     except:
         self.redirect('.')
Example #14
0
def image_detail(imageid):

    """
        function that is when a specific image is requested
        the metadata of the requested image is loaded (if there is one)
        and given to the template
    """

    try: 
        image = Image.get(id=imageid)
        imgfrag = ImageFragment.get(image=image, x=0, y=0, visible=True)
        imgmeta = Metadata.get(imgfrag=imgfrag, namespace="http://www.w3.org/ns/ma-ont#")
        annos = Annotation.get(imgmeta=imgmeta)
        return render_template('image_detail.html', img=image,imgmeta=imgmeta)
    except Imageuri.DoesNotExist:
        flash('Die Bildnummer wurde nicht gefunden. Bitte waehle ein anderes Bild.', 'error')
        return render_template('images.html')
    except ImageFragment.DoesNotExist:
        return render_template('image_detail.html', img=image)
def download_photo():
    global per_page
    global status
    r = randint(0, int(per_page))
    result = upload_photos()
    result = result[r]
    image_obj = Image.get_or_none(pixabay_id=result['id'])
    error = True

    while error:
        if image_obj is None:
            try:
                url = result["largeImageURL"]
                print(url)
                filename = url.split('/')[-1]
                script_path = os.path.dirname(__file__)
                rel_path = 'images/{}'.format(filename)
                path = os.path.join(script_path, rel_path)
                time.sleep(5)
                r = requests.get(url, allow_redirects=True)
                open(path, 'wb').write(r.content)
                image = save_to_db(result, path, url)
                return image
            except IOError as e:
                return e

        if image_obj.status == "Posted":
            i = 0
            status = True
            while i <= int(per_page) and status:
                n = randint(0, int(per_page) - 1)
                result = upload_photos()[n]
                image_obj = Image.get_or_none(pixabay_id=result['id'])
                if image_obj.status == "Not Posted":
                    print("Image already downloaded and in database")
                    image = Image.get(pixabay_id=result['id'])
                    return image
                else:
                    i += 1
                    status = True
            per_page = int(per_page) + 10
        error = False
Example #16
0
 def post(self):
     user = self.current_user
     content = self.get_argument('content', None)
     image_ids = self.get_argument('image_ids', None)
     images = []
     if not (content and len(strip_tags(content)) >= 3):
         result = {'status': 'error', 'message': '推文内容至少 3 字符'}
         return self.send_result(result, '/timeline')
     tweet = Tweet(content=strip_xss_tags(content), user_id=user.id).save()
     tweet.put_notifier()
     if image_ids:
         image_ids = image_ids.split(',')
         for image_id in image_ids:
             image_id = int(image_id)
             image = Image.get(id=image_id)
             if not image:
                 continue
             image.tweet_id = tweet.id
             images.append({
                 'id': image.id,
                 'path': image.path,
                 'width': image.width,
                 'height': image.height,
             })
     if images:
         tweet.has_img = 'true'
     result = {
         'status': 'success',
         'message': '推文创建成功',
         'content': tweet.content,
         'name': tweet.author.name,
         'nickname': tweet.author.nickname,
         'author_avatar': tweet.author.get_avatar(size=48),
         'author_url': tweet.author.url,
         'author_name': tweet.author.name,
         'author_nickname': tweet.author.nickname,
         'tweet_url': tweet.url,
         'created': tweet.created,
         'id': tweet.id,
         'images': images,
     }
     return self.send_result(result, '/timeline')
Example #17
0
    def get(self, image_key):
        img = Image.get(image_key)

        width = int(self.request.GET.get("width", "300"))

        # If no ratio we need to compute the ratio first thing
        # this is a small performance hit the first time.

        if img.ratio is None:
            thumb = img.get_thumb(width, commit=False)
            img.ratio = float(thumb.height) / float(thumb.width)
            db.put([thumb, img])

        height = int(float(width) * img.ratio)

        path = os.path.join(os.path.dirname(__file__), "templates", "crop.html")

        self.response.out.write(
            template.render(path, {"img": img, "width": width, "height": height, "IMAGE_APP_PATH": IMAGE_APP_PATH})
        )
Example #18
0
 def delete(self, image_id):
     image = Image.get(id=image_id)
     if not image:
         return self.redirect_next_url()
     if self.current_user.is_admin and image.user_id != self.current_user.id:
         subject = "图片删除通知 - " + config.site_name
         template = (
                 '<p>尊敬的 <strong>%(nickname)s</strong> 您好!</p>'
                 '您在 %(site) 的图片由于违反社区规定而被删除。</p>'
                 ) % {
                         'nickname': image.author.nickname,
                         'site': config.site_name,
                         }
         self.send_email(self, image.author.email, subject, template)
     if image.user_id == self.current_user.id:
         image.remove()
         result = {'status': 'success', 'message': '已成功删除'}
     else:
         result = {'status': 'error', 'message': '你没有权限啊, baby'}
     return self.write(result)
Example #19
0
def grab_post(req):
  """ Gets a post and validates the answers. """
  sec_okay = 1
  image_ans = req.get('word', None)
  image_id = req.get('image_id', None)
  sec_id = req.get('sec_id', None)
  sec_ans = req.get('sec_ans', None) 
  
  truth_file = Image.get(Image.id == image_id)
  with open(truth_file.answer, 'r') as file:
    image_truth = file.readline().strip()
 
  s = Secondary.get(Secondary.id == sec_id)
  known = s.known(2, 0.85)
  if ((image_ans == image_truth) and
      (not known or (known and (s.truth['word'] == sec_ans))) ):
    sec_update(sec_id, sec_ans)    
    return True
  else:
    return False
Example #20
0
    def post(self):
        item = None
        vals = {}

        # get all the incoming values
        title = self.request.get('title').strip()
        blob_key = None
        caption = self.request.get('caption').strip()
        credit_who = self.request.get('credit_who').strip()
        credit_link = self.request.get('credit_link').strip() if self.request.get('credit_link') else None
        label_raw = self.request.get('label_raw').strip()

        # get the file information
        uploaded_files = self.get_uploads('image')
        if len(uploaded_files) == 1:
            blob_info = uploaded_files[0]
            blob_key = blob_info.key()

        if self.request.get('key'):
            item = Image.get( self.request.get('key') )
            item.title       = title
            item.caption     = caption
            item.credit_who  = credit_who
            item.credit_link = credit_link
            item.label_raw   = label_raw
        else:
            item = Image(
                title       = title,
                caption     = caption,
                credit_who  = credit_who,
                credit_link = credit_link,
                label_raw   = label_raw,
                )

        if blob_key:
            item.blob = blob_key

        # update and save this image
        item.set_derivatives()
        item.put()
        self.redirect('.')
Example #21
0
 def delete(self, image_id):
     image = Image.get(id=image_id)
     if not image:
         return self.redirect_next_url()
     if image.topic_id:
         return self.send_error_result(msg=u'此图片被主题《%s》引用,无法删除' %
                                       image.topic.title)
     if self.current_user.is_admin and image.user_id != self.current_user.id:
         subject = "图片删除通知 - " + config.site_name
         template = ('<p>尊敬的 <strong>%(nickname)s</strong> 您好!</p>'
                     '您在 %(site)s 的图片由于违反社区规定而被删除。</p>') % {
                         'nickname': image.author.nickname,
                         'site': config.site_name,
                     }
         self.send_email(self, image.author.email, subject, template)
     if self.current_user.is_admin or image.user_id == self.current_user.id:
         image.remove()
         result = {'status': 'success', 'message': '已成功删除'}
     else:
         result = {'status': 'error', 'message': '你没有权限啊, baby'}
     return self.write(result)
Example #22
0
    def get(self, key, size):
        img = Image.get(key)

        # Cache resized images in blobstore

        query = img.sized_images.filter("size = ", int(size))
        logging.debug("Image: query for size '%s' has %d items" % (size, query.count()))
        if query.count() == 0:
            # Store resized version
            data = images.resize(img.data, int(size))
            ri = ResizedImage()
            ri.data = db.Blob(data)
            ri.image = img
            ri.size = int(size)
            ri.put()
            self.response.out.write(data)
        else:
            # Return cached data
            self.response.out.write(query[0].data)

        self.response.headers["Content-Type"] = "image/png"
        self.response.headers["Cache-Control"] = "max-age=7200"
Example #23
0
 def get(self,key):
     try:
         image = Image.get(Key(key))
         self.render_template('editImage',{'image':image})
     except BadKeyError:
         self.render_template('editImage',{'error':"Image Not Found"})
Example #24
0
 def get(self, image_id):
     image_id = int(image_id)
     image = Image.get(id=image_id)
     if not image:
         raise tornado.web.HTTPError(404)
     return self.render("image/index.html", image=image)
Example #25
0
async def get_image(image_id: int):
    return await Image_Pydantic.from_queryset_single(Image.get(id=image_id))
Example #26
0
 def get(self, image_id):
     image_id = int(image_id)
     image = Image.get(id=image_id)
     if not image:
         raise tornado.web.HTTPError(404)
     return self.render("image/index.html", image=image)
Example #27
0
 def get(self, image_key):
     if len(image_key) < 30:
         self.send_blob(blobstore.BlobInfo.get(image_key))
     else:
         img = Image.get(image_key)
         self.send_blob(img.image)