Ejemplo n.º 1
0
 def upload_image(cls, img_obj):
     with get_session() as db_session:
         img_id = str(IdGenerator.gen())
         path_src = datetime.datetime.now().strftime('%Y-%m-%d')
         upload_src = os.path.join(UPLOAD_SRC, path_src)
         if not os.path.exists(upload_src):
             os.makedirs(upload_src)
         im = Img.open(img_obj)
         width, height = im.size
         file_format = im.format
         file_name = '.'.join([img_id, file_format.lower()])
         file_full_path = os.path.join(upload_src,
                                       file_name).replace('\\', '/')
         im.save(file_full_path)
         # 数据库存储
         img = Image()
         img.id = img_id
         img.name = file_name
         img.width = width
         img.height = height
         img.path = path_src
         img.status = cls.NORMAL
         db_session.add(img)
         img_dict = img.to_dict()
         img_dict["src"] = os.path.join(path_src,
                                        file_name).replace('\\', '/')
         db_session.commit()
     return img_dict
Ejemplo n.º 2
0
def create_forum_category(sub_forum_name, category_name, sub_category_list):
    with get_session() as db_session:
        sub_forum = db_session.query(SubForum).filter(
            SubForum.name == sub_forum_name).first()
        if sub_forum:
            sub_forum_id = sub_forum.id
            forum_category = db_session.query(ForumCategory).filter(
                ForumCategory.name == category_name).first()
            if not forum_category:
                category_id = IdGenerator.gen()
                forum_category = ForumCategory()
                forum_category.id = category_id
                forum_category.name = category_name
                forum_category.sub_forum_id = sub_forum_id
                db_session.add(forum_category)
            else:
                category_id = forum_category.id
            for sub_category_name in sub_category_list:
                sub_category = db_session.query(ForumSubCategory).filter(
                    ForumSubCategory.name == sub_category_name).first()
                if not sub_category:
                    sub_category = ForumSubCategory()
                    sub_category.category_id = category_id
                    sub_category.name = sub_category_name
                    db_session.add(sub_category)
        db_session.commit()
Ejemplo n.º 3
0
def upload_article_image():
    result = {'state': 'ok'}
    f = request.files['upload']
    try:
        with get_session() as db_session:
            file_name = f.filename
            _id = IdGenerator.gen()
            original_name = HashName.gen(_id, info="common")
            upload_src = config.IMG_UPLOAD_SRC
            file_format = file_name.split('.')[-1]
            if file_format and file_format.upper() == 'GIF':
                width = 0
                height = 0
                mode = 'GIF'
                file_format = file_format.upper()
                file_full_path = os.path.join(
                    upload_src, 'common',
                    '.'.join([original_name,
                              file_format.lower()])).replace('\\', '/')
                f.save(file_full_path)
            else:
                # 图像处理
                im = Img.open(f)
                # 长宽
                width, height = im.size
                # 格式
                file_format = im.format
                # 模式
                file_full_path = os.path.join(
                    upload_src, 'common',
                    '.'.join([original_name,
                              file_format.lower()])).replace('\\', '/')
                mode = im.mode
                im.save(file_full_path)
            # 数据库存储
            img = CommonImage()
            img.id = _id
            img.name = file_name
            img.url = original_name
            img.format = file_format
            img.width = width
            img.mode = mode
            img.height = height
            db_session.add(img)
            result.update({
                'id': str(_id),
                'fileName': f.filename,
                'name': original_name,
                'original': original_name,
                'src': img.img_full_url,
                'type': '.%s' % img.format,
                'url': config.MANAGE_URL + '/static/' + img.img_full_url,
                'uploaded': 1
            })
            db_session.commit()
    except Exception as e:
        print traceback.format_exc(e)
        result.update({'state': 'fail'})
    return jsonify(result)
Ejemplo n.º 4
0
def update_image_recommend_tag_detail():
    result = {
        'response': 'ok',
        'info': ''
    }
    _id = request.form.get('id')
    name = request.form.get('name')
    tag_ids = request.form.get('tag_ids')
    tag_id_list = tag_ids.split(',')
    try:
        if None in [name] or not tag_id_list:
            result.update({
                'response': 'fail',
                'info': u'请检查参数是否填写完整'
            })
        else:
            with get_session() as db_session:
                if not _id:
                    _new_id = IdGenerator.gen()
                    recommend_tag = ImageRecommendTags()
                    recommend_tag.id = _new_id
                    recommend_tag.name = name
                    for tag_id in tag_id_list:
                        recommend_tag_rel = ImageRecommendTagsRel()
                        recommend_tag_rel.tag_id = tag_id
                        recommend_tag_rel.recommend_tag_id = _new_id
                        db_session.add(recommend_tag_rel)
                    db_session.add(recommend_tag)
                else:
                    recommend_tag = db_session.query(ImageRecommendTags).get(_id)
                    if recommend_tag:
                        recommend_tag.name = name
                        has_tags = db_session.query(ImageRecommendTagsRel).filter(
                            ImageRecommendTagsRel.recommend_tag_id == _id
                        ).all()
                        has_tag_id_list = set([str(tag.tag_id) for tag in has_tags])
                        # 删除的标签关系
                        del_tag_id_list = has_tag_id_list - set(tag_id_list)
                        db_session.query(ImageRecommendTagsRel).filter(
                            ImageRecommendTagsRel.tag_id.in_(del_tag_id_list)
                        ).delete(synchronize_session=False)
                        # 新增的标签关系
                        add_tag_id_list = set(tag_id_list) - has_tag_id_list
                        for add_tag_id in add_tag_id_list:
                            new_tags_rel = ImageRecommendTagsRel()
                            new_tags_rel.recommend_tag_id = _id
                            new_tags_rel.tag_id = add_tag_id
                            db_session.add(new_tags_rel)
                    else:
                        result['response'] = 'fail'
                        result['info'] = u'当前对象不存在'
                db_session.commit()
        return jsonify(result)
    except Exception as e:
        app.my_logger.error(traceback.format_exc(e))
        abort(400)
Ejemplo n.º 5
0
def init_system_config(name, email, password):
    with get_session() as db_session:
        # 初始化管理员
        user_id = IdGenerator.gen()
        user = User()
        user.id = user_id
        user.name = name
        user.email = email
        user.password = AESCipher.encrypt(password)
        db_session.add(user)
        # 初始化角色
        role_id = IdGenerator.gen()
        role = Role()
        role.id = role_id
        role.name = u"管理员"
        db_session.add(role)
        # 关联关系
        user_role_rel = UserRoleRel()
        user_role_rel.role_id = role_id
        user_role_rel.user_id = user_id
        db_session.add(user_role_rel)
        db_session.commit()
Ejemplo n.º 6
0
def create_forum(forum_name, sub_forum_list):
    with get_session() as db_session:
        forum = db_session.query(Forum).filter(
            Forum.name == forum_name).first()
        if not forum:
            forum_id = IdGenerator.gen()
            forum = Forum()
            forum.id = forum_id
            forum.name = forum_name
            db_session.add(forum)
        else:
            forum_id = forum.id
        for sub_forum_name in sub_forum_list:
            sub_forum = SubForum()
            sub_forum.forum_id = forum_id
            sub_forum.name = sub_forum_name
            db_session.add(sub_forum)
        db_session.commit()
Ejemplo n.º 7
0
def bath_gen_discount_code(email, num, discount_id):
    try:
        with get_session() as db_session:
            user = db_session.query(User).filter(User.email == email).first()
            if user:
                _id = IdGenerator.gen()
                discount_history = DisocuntCodeGenHistory()
                discount_history.id = _id
                discount_history.creator_id = user.id
                discount_history.gen_num = num
                discount_history.creator_name = user.name
                db_session.add(discount_history)
                for i in range(num):
                    discount_code = DiscountCode()
                    discount_code.discount_id = discount_id
                    discount_code.code = gen_discount_code()
                    discount_code.history_id = _id
                    discount_code.status = DiscountCode.STATUS_NEW
                    db_session.add(discount_code)
            db_session.commit()
    except Exception as e:
        print traceback.format_exc(e)
Ejemplo n.º 8
0
def save_images(images, t=Image.TYPE_COMMON, series_ids=None, tag_ids=None):
    image_id_list = list()
    with get_session() as db_session:
        for image in images:
            _id = IdGenerator.gen()
            file_name = image.filename
            original_name = HashName.gen(_id, info="original")
            preview_name = HashName.gen(_id, info="preview")
            thumbnail_name = HashName.gen(_id, info="thumbnail")

            upload_src = config.IMG_UPLOAD_SRC

            # 图像处理
            im = Img.open(image)
            preview_im = im.copy()
            thumb_im = im.copy()
            # 长宽
            width, height = im.size
            # 格式
            file_format = im.format
            # 模式
            mode = im.mode
            im.save(
                os.path.join(upload_src, 'original',
                             '.'.join([original_name,
                                       file_format.lower()
                                       ])).replace('\\', '/'))
            # 预览图(高度固定)
            # 2018-02-26 预览图添加水印
            preview_height = int(config.PREVIEW_IMG_HEIGHT)
            preview_width = int(width / (float(height) / preview_height))
            preview_im.thumbnail((preview_width, preview_height))
            preview_im = add_watermark_text(preview_im,
                                            config.WATERMARK_IMG_FONT)
            preview_im.save(
                os.path.join(upload_src, 'preview',
                             '.'.join([preview_name,
                                       file_format.lower()
                                       ])).replace('\\', '/'))
            # 缩略图(等比例缩放)
            thumb_height = int(config.THUMBNAIL_IMG_HEIGHT)
            thumb_width = int(width / (float(height) / thumb_height))
            thumb_im.thumbnail((thumb_width, thumb_height))
            thumb_im.save(
                os.path.join(upload_src, 'thumbnail',
                             '.'.join([thumbnail_name,
                                       file_format.lower()
                                       ])).replace('\\', '/'))
            # 数据库存储
            img = Image()
            img.id = _id
            img.name = file_name
            img.type = t
            img.url = original_name
            img.preview_url = preview_name
            img.thumbnail_url = thumbnail_name
            img.format = file_format
            img.width = width
            img.mode = mode
            img.height = height
            img.color = get_image_color(thumb_im, z=10)
            db_session.add(img)

            # 关联专题
            if series_ids and series_ids[0]:
                for series_id in series_ids:
                    series = db_session.query(ImageSeries).get(series_id)
                    img_series = ImageSeriesRel()
                    img_series.image_id = _id
                    img_series.image_series_id = series_id
                    img_series.image_series_name = series.name
                    db_session.add(img_series)

            # 关联标签
            if tag_ids and tag_ids[0]:
                for tag_id in tag_ids:
                    tag = db_session.query(ImageTags).get(tag_id)
                    img_tag = ImageTagsRel()
                    img_tag.image_id = _id
                    img_tag.tag_id = tag_id
                    img_tag.tag_name = tag.name
                    db_session.add(img_tag)

            image_id_list.append(str(_id))
        db_session.commit()
    # 返回存储的图片id列表
    return image_id_list
Ejemplo n.º 9
0
            'modified_date': self.modified_date.strftime('%Y-%m-%d %H:%M:%S'),
            'view_count': self.view_count,
            'collect_count': self.collect_count
        }


class ImageSeriesRel(Base):
    __tablename__ = 'image_series_rel'

    id = Column(BigInteger, default=IdGenerator.gen, primary_key=True)
    # 图片ID
    image_id = Column(BigInteger, index=True)
    # 系列ID
    image_series_id = Column(BigInteger, index=True)
    # 系列名称
    image_series_name = Column(String(100), index=True)

    def to_dict(self):
        return {
            'id': str(self.id),
            'image_id': str(self.image_id),
            'image_series_id': str(self.image_series_id),
            'image_series_name': self.image_series_name,
            'created_date': self.created_date.strftime('%Y-%m-%d %H:%M:%S'),
            'modified_date': self.modified_date.strftime('%Y-%m-%d %H:%M:%S'),
        }


if __name__ == '__main__':
    print IdGenerator.gen()