示例#1
0
def create(data):
    product_id= data.get('product_id', '')
    product = Product.get_by_id(product_id)
    if not product:
        res = { 'api_success':False,
                'api_msg':'Product %s not found' % product_id,
                'api_function': create.__name__}
        logging.warning(res)
        return render_json_response(res)
    image64 = data.get('image_data', '')
    if not image64:
        res = {'api_success': False, 'api_msg': 'Image data not found'}
        logging.warning(res)
        return render_json_response(res)
    image64 = base64.decodestring(image64)
    im = Image.create_from_data(image64, title=product.title)
    if im.get_cached_url():
        if product.master_image is None:
            im.is_master = True
        product.images.append(im)
        product.put()
        res = {'api_success': True, 'api_msg': 'Image uploaded'}
        logging.info(res)
    else:
        res = {'api_success':False,
                 'api_msg':'Invalid image'}
        logging.warning(res)
    return render_json_response(res)
示例#2
0
def add_image(request, name):
    product_ = Product.get_by_id(name)
    if not product_:
        return render_json_response({'api_success':False,
                                     'api_msg':'Product %s not found' % name},
                                    status=400)
    if request.method == 'POST':
        try:
            upload_files = get_uploads(request, 'file')
            blob_info = upload_files[0]
            im = Image.create(blob_info.key(), title=product_.title)
            if not len(product_.images):
                im.is_master = True
            if im.get_cached_url():
                product_.images.append(im)
                product_.put()
                api_upload_img_url = blobstore.create_upload_url(
                                    url_for('shop/admin/product/upload_img',
                                        name=product_.key.id()))
                return render_json_response(
                    {'api_success':True,
                     'api_msg':'Image uploaded',
                     'api_upload_img_url':api_upload_img_url,
                     'img': im.to_json()})
            else:
                return render_json_response(
                            {'api_success':False,
                             'api_msg':'Invalid image'})
        except Exception, e:
            return render_json_response(
                    {'api_success':False,
                     'api_msg':str(e)}, status=400)
示例#3
0
def delete(request):
    image_key = request.values.get('img_key')
    if image_key:
        img = Image.get(image_key)
        if img:
            img.delete()
    return Response('Ok')
示例#4
0
    def load_demo_explorations(cls):
        """Initializes the demo explorations."""
        for index, exploration in enumerate(feconf.DEMO_EXPLORATIONS):
            assert len(exploration) in [3, 4], "Invalid format for demo exploration: %s" % exploration

            yaml_filename = "%s.yaml" % exploration[0]
            yaml_file = utils.get_file_contents(os.path.join(feconf.SAMPLE_EXPLORATIONS_DIR, yaml_filename))

            title = exploration[1]
            category = exploration[2]
            image_filename = exploration[3] if len(exploration) == 4 else None

            image_id = None
            if image_filename:
                with open(os.path.join(feconf.SAMPLE_IMAGES_DIR, image_filename)) as f:
                    raw_image = f.read()
                image_id = Image.create(raw_image)

            exploration = cls.create_from_yaml(
                yaml_file=yaml_file,
                user=None,
                title=title,
                category=category,
                exploration_id=str(index),
                image_id=image_id,
            )
            exploration.is_public = True
            exploration.put()
示例#5
0
def upload(request):
  upload_url = blobstore.create_upload_url(url_for('image/admin/add'))
  blob_key = request.values.get('img_key')
  d = {'upload_url': upload_url}
  if blob_key:
    d['image'] = Image.get(blob_key)
  return render_to_response("image/admin/upload.html", d)
示例#6
0
 def post(self):
     """Saves an image uploaded by a content creator."""
     raw = self.request.get('image')
     if raw:
         image_id = Image.create(raw)
         self.render_json({'image_id': image_id})
     else:
         raise self.InvalidInputException('No image supplied')
示例#7
0
def add(request):
    if request.method == 'POST':
        upload_files = get_uploads(request, 'file')
        blob_info = upload_files[0]
        im = Image.create(blob_info.key())
        headers = {'Location': url_for('image/admin/upload', img_key=im.key())}
    else:
        headers = {'Location': url_for('image/admin/upload')}
    return Response(None, headers=headers, status=302)
示例#8
0
def img_tag(environment, value, prefix=''):
    if value is None:
        return ''
    i = memcache.get(value)
    if i is None:
        i = Image.get(value)
        if i:
            memcache.add(value, i, 7200)
    if i:
        return Markup(i.get_img_tag(prefix))
    return ''
示例#9
0
def internal_thumb_image(value, size="700x700"):
    if value is None:
        return ''
    thumb = ThumbImage.get(value)
    if thumb:
        try:
            att = getattr(thumb, "thumb_%s" % size)
        except AttributeError:
            return ''
        return Image.get(att).image
    return ''
示例#10
0
def link(environment, value):
    if value is None:
        return ''
    i = memcache.get(value)
    if i is None:
        i = Image.get(value)
        if i:
            memcache.add(value, i, 7200)
    if i:
        return Markup(i.get_link())
    return ''
示例#11
0
def get_img_url(key):
    img = ThumbImage.get(key)
    img_url = ''
    if img:
        try:
            att = getattr(img, "thumb_700x700")
            i = Image.get(att)
            img_url = i.get_link()
        except AttributeError:
            img_url = ''
    if img_url:
        return 'www.5studio.ru%s' % img_url
    return ''
示例#12
0
    def get(self, image_id):
        """Returns an image.

        Args:
            image_id: string representing the image id.
        """
        image = Image.get_by_id(image_id)
        if image:
            # TODO(sll): Support other image types.
            self.response.headers['Content-Type'] = str('image/%s' % image.format)
            self.response.write(image.raw)
        else:
            self.response.write('No image')
示例#13
0
def get_mini_main_thumb_url(gift):
    thumb_url = ''
    if gift.main_thumb:
        thumb = ThumbImage.get(gift.main_thumb)
        if thumb:
            try:
                att = getattr(thumb, "thumb_100x100")
                i = Image.get(att)
                thumb_url = i.get_link()
            except AttributeError:
                pass
        if thumb_url:
            return 'www.5studio.ru%s' % thumb_url
    return ''
示例#14
0
def get_main_img_url(gift):
    img_url = ''
    if gift.main_thumb:
        img = ThumbImage.get(gift.main_thumb)
        if img:
            try:
                att = getattr(img, "thumb_700x700")
                i = Image.get(att)
                img_url = i.get_link()
            except AttributeError:
                pass
        if img_url:
            return 'www.5studio.ru%s' % img_url
    return ''
示例#15
0
def get_thumb_url(key, thumb_size = "400x400"):
    thumb_size_ = "thumb_%s" % thumb_size
    thumb = ThumbImage.get(key)
    thumb_url = ''
    if thumb:
        try:
            att = getattr(thumb, thumb_size_)
            i = Image.get(att)
            thumb_url = i.get_link()
        except AttributeError:
            thumb_url = ''
    if thumb_url:
        return 'www.5studio.ru%s' % thumb_url
    return ''
示例#16
0
    def get(self, image_id):
        """Returns an image.

        Args:
            image_id: string representing the image id.
        """
        try:
            image = Image.get(image_id)

            # TODO(sll): Support other image types.
            self.response.headers['Content-Type'] = str('image/%s' % image.format)
            self.response.write(image.raw)
        except:
            raise self.PageNotFoundException
示例#17
0
def send_newsletter_task(request, user_key, newsletter_key):
    newsletter = Newsletter.get(newsletter_key)
    managers = []
    message = mail.EmailMessage(sender=settings.DEFAULT_MAIL_FROM, subject=newsletter.title)
    user = UserProfile.get(user_key)
    message.to = user.email
    if not message.to:
        return Response("Ok")

    gifts = []
    gifts_images = {}
    if newsletter.gifts:
        gifts_split = newsletter.gifts.split(",")
        for gift in gifts_split:
            try:
                gift = gift.strip()
                obj = Gift.all().filter("uid =", gift).get()
                if obj:
                    gifts.append(obj)
                    if obj.main_thumb:
                        try:
                            img = ThumbImage.get(obj.main_thumb)
                            img = Image.get(img.thumb_200x200)
                            if img:
                                gifts_images[obj.uid] = base64.b64encode(str(img.image))
                        except Exception:
                            pass
            except Exception:
                pass

    message_text = render_to_string(
        "postman/send_newsletter.html",
        {"newsletter": newsletter, "gifts": gifts, "managers": managers, "gifts_images": gifts_images},
    )
    message.html = message_text
    attachments = []
    for file_key in newsletter.n_price_list:
        file_ = File.get(file_key)
        if file_ and file_.blob_key:
            bi = blobstore.BlobInfo.get(file_.blob_key)
            if bi:
                attachments.append(("%s" % file_.title_filename, bi.open().read()))
    message.attachments = attachments
    message.send()
    return Response("OK")
示例#18
0
文件: admins.py 项目: gmist/1businka
def upload_image(request, id):
    union = Union.get_by_id(id)
    if not union:
        return render_json_response({"api": {"success": False, "msg": "Union %s not found" % id}}, status=400)
    if request.method == "POST":
        try:
            upload_files = get_uploads(request, "file")
            blob_info = upload_files[0]
            im = Image.create(blob_info.key(), title=union.title)
            if not len(union.images):
                im.is_master = True
            if im.get_cached_url():
                union.images.append(im)
                union.put()
                return render_json_response({"api_success": True, "api_msg": "Image uploaded", "image": im.to_json()})
            else:
                return render_json_response({"api_success": False, "api_msg": "Invalid image"})
        except Exception, e:
            return render_json_response({"api_success": False, "api_msg": str(e)}, status=400)
示例#19
0
def get_image(request, thumb_key):
    thumb_key=string.rsplit(thumb_key, '.', maxsplit=1)[0]
    im = memcache.get(thumb_key)
    if not im:
        try:
            im = Image.get(thumb_key)
        except BadKeyError:
            return Response(status=404)
        if im:
            memcache.add(thumb_key, im, 28*24*60*60)
    if im:
        headers = Headers()
        headers['Content-Type'] = im.content_type
        headers['Last-Modified'] = im.modif_time.strftime(HTTP_DATE_FMT)
        current_day = datetime.today()
        exp_delta = timedelta(days=7)
        headers['Expires'] = (current_day + exp_delta).strftime(HTTP_DATE_FMT)
        return Response(im.image, headers=headers)
    return Response(status=404)
示例#20
0
def add_image(request, uid):
    category = Category.get_by_id(uid)
    if not category:
        return render_to_response('empty.html')
    if request.method == 'POST':
        try:
            upload_files = get_uploads(request, 'file')
            if len(upload_files):
                blob_info = upload_files[0]
                if blob_info.size:
                    im = Image.create(blob_info.key(), title=category.title)
                    if not len(category.images):
                        im.is_master = True
                    if im.get_cached_url():
                        category.images.append(im)
                        category.put()
                        return images(request, uid)
                else:
                     blob_info.delete()
        except Exception, e:
            return render_to_response('empty.html', {'msg': msg})
示例#21
0
def brand_add_image(request, brand_key):
    if request.method == 'POST':
        try:
            brand = Brand.get_by_id (brand_key)
            img = Image.create_from_data(
                blob_data=request.files['file'].read(),
                format=request.files['file'].content_type)
            if img.get_cached_url():
                brand.images.append(img)
                brand.put()
                return render_json_response({'api_success': True,
                                         'api_msg': 'BrandImage created'})
            else:
                return render_json_response(
                            {'api_success':False,
                             'api_msg':'Invalid image'})
        except apiproxy_errors.RequestTooLargeError:
            return render_json_response({'api_success': False,
                             'api_msg': u'Файл слишком большой. '
                                        u'Размер файла должен быть мешьше 1 мегабайта.'})
        except Exception, e:
            return render_json_response({'api_success': False,
                                         'api_msg': str(e)})
示例#22
0
def write_category(wb, category, all=False):
    if category.gifts:
        ws = wb.add_sheet(category.name)
        if all:
            gifts = category.gifts
        else:
            gifts = category.gifts.filter('in_trash =', False).filter('leftovers >', 0)
        write_head(ws)
        for i, g in enumerate(gifts):
            url = 'http://www.5studio.ru/g/%s/' % g.uid
            ws.write(i + 1, 0, xlwt.Formula('HYPERLINK("%s")' % url))
            if g.main_thumb:
                img = ThumbImage.get(g.main_thumb)
                if img and getattr(img, 'thumb_100x100'):
                    img = "http://www.5studio.ru%s" % Image.get(img.thumb_100x100).get_link()
                    ws.write(i + 1, 1, xlwt.Formula('HYPERLINK("%s")' % img))
            ws.write(i + 1, 2, g.catalogue_id)
            ws.write(i + 1, 3, g.barcode)
            ws.write(i + 1, 4, g.name)
            ws.write(i + 1, 5, g.category.name)
            ws.write(i + 1, 6, g.group.name)
            ws.write(i + 1, 7, g.brand)
            ws.write(i + 1, 8, g.price)
            ws.write(i + 1, 9, g.real_price)
示例#23
0
def send_newsletter_task2(request, email, newsletter_key_id):
    newsletter = Newsletter2.get_by_id(newsletter_key_id)

    managers = []
    for mgr_id in newsletter.managers:
        mgr = Manager.get_by_id(mgr_id)
        if mgr:
            managers.append(mgr)

    message = mail.EmailMessage(sender=settings.DEFAULT_MAIL_FROM, subject=newsletter.title)
    message.to = email
    if not message.to:
        return Response("Ok")
    mangers_emails = [manager.email for manager in managers]
    if mangers_emails:
        message.reply_to = ",".join(mangers_emails)

    gifts = []
    gifts_images = {}
    if newsletter.gifts:
        gifts_split = newsletter.gifts.split(",")
        for gift in gifts_split:
            try:
                gift = gift.strip()
                obj = Gift.all().filter("uid =", gift).get()
                if obj:
                    gifts.append(obj)
                    if obj.main_thumb:
                        try:
                            img = ThumbImage.get(obj.main_thumb)
                            img = Image.get(img.thumb_200x200)
                            if img:
                                gifts_images[obj.uid] = base64.b64encode(str(img.image))
                        except Exception:
                            pass
            except Exception:
                pass

    message_text = render_to_string(
        "postman/send_newsletter2.html",
        {"newsletter": newsletter, "gifts": gifts, "managers": managers, "gifts_images": gifts_images},
    )
    message.html = message_text
    attachments = []
    for file_key in newsletter.n_price_list:
        file_ = File.get(file_key)
        if file_ and file_.blob_key:
            bi = blobstore.BlobInfo.get(file_.blob_key)
            if bi:
                attachments.append(("%s" % file_.title_filename, bi.open().read()))
    if attachments:
        message.attachments = attachments
    try:
        message.send()
    except apiproxy_errors.OverQuotaError:

        def txn():
            taskqueue.add(
                url=url_for("postman/send_newsletter_task2", email=email, newsletter_key_id=newsletter_key_id),
                transactional=True,
            )

        db.run_in_transaction(txn)
    return Response("OK")