Example #1
0
def init_image():
    user_default = UserProfile.objects.get(email='*****@*****.**')
    cur_sqlite = db_sqlite.cursor()
    cur_sqlite.execute(
        "select name,url_image,url_thumb,width,height,file_type,category_id,tags from image"
    )

    for item in cur_sqlite.fetchall():
        image = Image()
        image.name = item[0]
        image.url = item[1]
        image.url_thumb = item[2]
        image.width = item[3]
        image.height = item[4]
        image.type = item[5].replace('.', '')

        image.user = user_default
        image.save()

        category_id = item[6]
        if category_id != '':
            category = Category.objects.get(pk=int(item[6]))
            category.count += 1
            category.save()
            image.categorys.add(category)

        tags_info = item[7]
        if tags_info != '':
            tags_info = "{'tags':" + tags_info + "}"
            tags_info = tags_info.replace("'tags'", '"tags"') \
                .replace("'name'", '"name"') \
                .replace("'id'", '"id"') \
                .replace(": '", ': "') \
                .replace("', ", '", ') \
                .replace("'}", '"}')
            try:
                tags_info = json.loads(tags_info)
            except Exception as e:
                logging.error(tags_info)
                pass
            try:
                for item in tags_info['tags']:
                    try:
                        tag = Tag.objects.get(name=item['name'])
                        tag.count += 1
                        tag.save()
                        image.tags.add(tag)
                    except Exception as e:
                        tag = Tag()
                        tag.name = item['name']
                        tag.count = 1
                        tag.save()
                        image.tags.add(tag)
            except Exception as e:
                logging.error(tags_info)
                logging.error(e)
def create_images():

	Image.objects.all().delete()

	for pk, fields in imagenes.iteritems():

		im = Image(pk=pk)
		im.order = fields['order']
		im.user_id = get_user(fields['user'])
		im.width = fields['width']
		im.height = fields['height']

		file_name = fields['image'].split('/')[-1]
		#result = urllib.urlretrieve('http://datea.pe/media/'+fields['image'])
		im.image.save(file_name, File(open('impdata/'+fields['image'])))
		im.client_domain = datea
		im.save()
Example #3
0
def exe_registration(blog_info_list, post_date, group_id, all_check, tweet, console):
    """
    ブログの登録処理
    Args:
        blog_info_list (list): ブログ情報のリスト。前提としてリストの中のブログは同じpost_dateを持つ。
        post_date (date): 共通のpost_date
        group_id (int): グループID
        all_check (bool): 保存済みのブログを見つけても処理を実行
        tweet (bool): 更新通知をtweetするか否か
        console (bool): ログ出力するか否か
    Returns:
        True(登録処理終了), False(登録処理続行)
    """
    download_count = 0
    blog_objects = []
    image_objects = []

    for i, blog_info in enumerate(blog_info_list):
        # new blog
        if not Blog.objects.filter(blog_ct=blog_info['blog_ct'], publishing_group__group_id=group_id).exists():
            blog = Blog(
                blog_ct=blog_info['blog_ct'],
                title=blog_info['title'],
                post_date=post_date,
                order_for_simul=i,
                writer=blog_info['member'],
                publishing_group=Group.objects.filter(
                    group_id=group_id).first(),
            )
            blog_objects.append(blog)
            download_count += 1
        # already saved
        else:
            blog = Blog.objects.get(
                blog_ct=blog_info['blog_ct'], publishing_group__group_id=group_id)

        if len(blog_info['image_urls']) > 0:
            order = 0
            for image_url in blog_info['image_urls']:
                if not Image.objects.filter(publisher=blog).exists():
                    media = otapick.BlogImageDownloader().download(
                        image_url, group_id, blog.blog_ct, blog.writer.ct)
                    if media == 'not_image':  # exclude gif
                        pass
                    elif media is not None:
                        image = Image(
                            order=order,
                            picture=media,
                            publisher=blog,
                        )

                        # set width & height
                        w, h = otapick.get_image_w_h(image)
                        image.width = w
                        image.height = h

                        image_objects.append(image)
                        order += 1
                    else:
                        import traceback
                        traceback.print_exc()

        # change the order_for_simul of already saved blog with the same post_date
        if Blog.objects.filter(post_date=post_date).exists():
            for saved_simultime_blog in Blog.objects.filter(post_date=post_date):
                saved_simultime_blog.order_for_simul += download_count
                saved_simultime_blog.save()

    # save new blog
    for blog_object in blog_objects:
        blog_object.save()
        if console:
            otapick.print_console(
                'register 「' + blog_object.title + '」 written by ' + blog_object.writer.full_kanji)

    # save new image
    for image_object in image_objects:
        image_object.save()
        otapick.compress_blog_image(image_object)

    # tweet update info
    if tweet:
        updateBot = otapick.UpdateBot()
        for blog_object in blog_objects:
            updateBot.tweet(
                group_id=blog_object.publishing_group.group_id, blog_ct=blog_object.blog_ct)

    # When there is at least one already saved blog in blog_list and all_check is False
    if download_count != len(blog_info_list) and not all_check:
        return True

    # When all blog in blog_list are new or when all_check is True
    else:
        return False
Example #4
0
    def post(self, request):
        all_category = Category.objects.all()
        images = request.FILES.getlist("image_file")
        categorys = request.POST.getlist("image_category")
        description = request.POST.get("image_description")
        tags = request.POST.get('image_tag', '')
        if tags != '' and tags.find('|'):
            tags = tags.split('|')

        all_file_url = []
        upload_path = os.path.join(settings.MEDIA_ROOT, 'release')
        upload_path_thumb = os.path.join(settings.MEDIA_ROOT, 'release_thumb')
        if images:
            for image in images:
                md5 = hashlib.md5()
                for chrunk in image.chunks():
                    md5.update(chrunk)
                name = image.name
                size = image.size
                type = os.path.splitext(name)[-1]
                md5_name = md5.hexdigest()

                img_path = os.path.join(upload_path, md5_name) + type
                img_path_thumb = os.path.join(upload_path_thumb,
                                              md5_name) + type

                url = os.path.join(settings.MEDIA_URL, 'release',
                                   md5_name) + type
                url_thumb = os.path.join(settings.MEDIA_URL, 'release_thumb',
                                         md5_name) + type

                all_file_url.append(url_thumb)

                img = open(img_path, 'wb')
                for chrunk in image.chunks():
                    img.write(chrunk)
                img.close()

                pimg = PImage.open(img_path)

                _img = Image()
                _img.user = request.user
                _img.name = name
                _img.description = description
                _img.url = url
                _img.url_thumb = url_thumb
                _img.size = size
                _img.width, _img.height = pimg.size
                _img.type = type.strip('.')
                _img.save()

                pimg.thumbnail((300, 300))
                pimg.save(img_path_thumb)

                if len(categorys) == 0:
                    category = Category.objects.get(name='Other')
                    category.count += 1
                    category.save()
                    _img.categorys.add(category)
                else:
                    for category_id in categorys:
                        category = Category.objects.get(pk=category_id)
                        category.count += 1
                        category.save()
                        _img.categorys.add(category)

                if len(tags) == 0:
                    tag = Tag.objects.get(name='Other')
                    tag.count += 1
                    tag.save()
                    _img.tags.add(tag)

                else:
                    for tag_name in tags:
                        tag = None
                        try:
                            tag = Tag.objects.get(name=tag_name)
                        except:
                            pass
                        if tag:
                            tag.count += 1
                            tag.save()
                            _img.tags.add(tag)
                        else:
                            tag = Tag()
                            tag.name = tag_name
                            tag.user = request.user
                            tag.count += 1
                            tag.save()
                            _img.tags.add(tag)
                _img.save()

            return render(
                request, 'user/release.html', {
                    'message': '文件上传成功!',
                    'all_file_url': all_file_url,
                    'all_category': all_category,
                })
        else:
            return render(request, 'user/release.html', {
                'message': '请先选择需要上传的文件!',
                'all_category': all_category,
            })