Пример #1
0
def get_post_admin(data):
    try:
        id = data['id']
        filter = data.get('filter')
        if id and filter == 'state_publish':
            data = select('posts',
                          fields=[
                              'id', 'title', 'create_time', 'summary', 'class',
                              'tags', 'url'
                          ],
                          where={'id': id})
        elif id:
            data = select('posts',
                          fields=[
                              'id', 'title', 'create_time', 'summary', 'posts',
                              'code_style', 'class', 'tags', 'url'
                          ],
                          where={'id': id})
        if len(data) > 1:
            log.error(
                'func:get_post_admin|post_id:{}|post number > 1'.format(id))
            return False, ''
        else:
            data = data[0]
            data['tags'] = list(map(int, data['tags'].split(',')))
            return True, data
    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #2
0
def get_tags_list(data=None):
    try:
        fields = ['id', 'tagname', 'status', 'intro']
        if data:
            with_op = data.get('with', '').strip()
            if with_op == 'with_page':
                page_num = int(data['page_num'])
                tag_num_per_page = int(data['tag_num_per_page'])
                offset = (page_num - 1) * tag_num_per_page
                data = select('tags',
                              fields=fields,
                              where={'status': [1, 2]},
                              sort_field='id',
                              limit=tag_num_per_page,
                              offset=offset)
                total_num_sql = r'''select count(id) from `tags` where `status` in (1, 2);'''
                state = g.db.query(total_num_sql)
                if state[0]:
                    total_tag_num = g.db.cur.fetchone()[0]
                    return_data = {
                        'list_data': data,
                        'total_tag_num': total_tag_num
                    }
                    return True, return_data

        data = g.db.select('tags', fields=fields, where={'status': [1, 2]})
        if data[0]:
            return True, data[1][1]
        else:
            return False, ''
    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #3
0
def save_post(data):
    ''' 通过id判断是更新还是创建。  在第一次保存草稿以后,会返回id值,便于第二次保存变为更新 '''
    try:
        title = data['title']
        content = data['content']
        code_style = data['code_style']
        id = data['id']

        timestamp_now = int(datetime.datetime.now().timestamp())
        write_data = {
            'title': title,
            'posts': content,
            'status': 2,
            'code_style': code_style
        }
        if id:
            write_data['update_time'] = timestamp_now
            state = g.db.update('posts', write_data, where={'id': id})
            # 如果没有更新成功,前端提示注意保存本地
            if state[0] and state[1]:
                return True, ''
        else:
            write_data['create_time'] = timestamp_now
            write_data['update_time'] = timestamp_now
            write_data['id'] = timestamp_now
            state = g.db.insert('posts', write_data)
            if state[0] and state[1]:
                id = select('posts', fields=['id'], where={'title':
                                                           title})[0]['id']
                if id:
                    return True, {'id': id}
    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #4
0
def handle_post_info(data):
    ''' 添加标签, 处理时间戳为字符串格式,处理状态码为文字 '''
    ''' 为了不让前端在重新处理一遍, 就在这里处理了 '''
    tags_list = set()  # 为了添加标签
    classes_list = set()
    status_data = {1: '已发布', 2: '草稿', 3: '已删除'}
    strftime = r'%Y-%m-%d %H:%M'
    for note in data:
        if 'create_time' in note:
            create_timestamp = note['create_time']
            timestamp_obj = datetime.datetime.fromtimestamp(create_timestamp)
            note['create_time'] = timestamp_obj.strftime(strftime)
        if 'update_time' in note:
            update_timestamp = note['update_time']
            timestamp_obj = datetime.datetime.fromtimestamp(update_timestamp)
            note['update_time'] = timestamp_obj.strftime(strftime)
        if 'class' in note:
            classes_list.add(note['class'])
        if 'tags' in note:
            for tag_id in note['tags'].split(','):
                tags_list.add(tag_id)
        if 'status' in note:
            note['status_str'] = status_data[note['status']]

    if tags_list:
        tags_data = select('tags',
                           fields=['id', 'tagname'],
                           where={'id': list(tags_list)})
        tags_dict = {tag['id']: tag['tagname'] for tag in tags_data}

    if classes_list:
        classes_data = select('class',
                              fields=['id', 'classname'],
                              where={'id': list(classes_list)})
        classes_dict = {clas['id']: clas['classname'] for clas in classes_data}

    for note in data:
        tag_list = []
        for tag_id in note['tags'].split(','):
            try:
                tag_list.append(tags_dict[int(tag_id)])
            except KeyError:
                pass
        note['tags_str'] = ','.join(tag_list)
        note['classes_str'] = classes_dict.get(note['class'], '')

    return data
Пример #5
0
def get_static_notice_fw():
    try:
        notice = select('notice', fields=['content'], where={'id': 1, 'type': 1, 'status': 1})
        if notice[0]:
            return True, notice
    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #6
0
def invalid_attach(data):
    '''失效附件'''
    try:
        filename = data.get('file_name', '').strip()
        file_id = int(data.get('file_id', 0))
        only_filename, ext_name = filename.split('.')
        file_info = select('attach',
                           fields=['pathname', 'private', 'status'],
                           where={
                               'filename': filename,
                               'id': file_id
                           })[0]
        if file_info:
            pathname = file_info['pathname']
            private = file_info['private']
            status = file_info['status']
            if status == 2:
                return False, 'file already invalid'

            invalid_filename = '{}_{}.{}'.format(only_filename, 'invalid',
                                                 ext_name)
            invalid_file_pathname = os.path.dirname(pathname) + '/{}'.format(
                invalid_filename)
            if private == 1:
                src_file_pathname = basedir / pathname
                dest_file_pathname = basedir / invalid_file_pathname
            elif private == 2:
                src_file_pathname = basedir / private_data_dir / pathname
                dest_file_pathname = basedir / private_data_dir / invalid_file_pathname
            else:
                log.error(
                    'fund:invalid_attach|private:{}|private is error'.format(
                        private))
                return False, ''
            try:
                g.db.begin()
                state = g.db.update('attach', {'status': 2},
                                    where={
                                        'filename': filename,
                                        'id': file_id
                                    })
                if state[0] and state[1] == 1:
                    os.rename(src_file_pathname, dest_file_pathname)
                    g.db.commit()
                    return True, ''
                else:
                    g.db.rollback()
                    log.error(
                        'fund:invalid_attach|state:{}|db exec state is error'.
                        format(state))
            except Exception:
                log.error(traceback.format_exc())
                g.db.rollback()

    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #7
0
def make_mini_photo(filename, size_level):
    try:
        level = {
            1: (64, 64),
            2: (128, 128),
            3: (256, 256),
            4: (512, 512),
            5: (1024, 1024),
            6: (2048, 2048),
            7: (4096, 4096)
        }
        file_info = select(
            'attach',
            fields=['pathname', 'mimetype', 'private', 'is_image'],
            where={'filename': filename})[0]
        if file_info:
            pathname = file_info['pathname']
            is_image = file_info['is_image']
            private = file_info['private']

            only_filename, ext_name = filename.split('.')

            if is_image == 1:
                mini_filename = '{}_{}.{}'.format(only_filename,
                                                  level[size_level][0],
                                                  ext_name)
                mini_file_pathname = os.path.dirname(pathname) + '/{}'.format(
                    mini_filename)

                if private == 1:
                    url_path = '{}/{}'.format(site_url, mini_file_pathname)
                    src_file_pathname = basedir / pathname
                    dest_file_pathname = basedir / mini_file_pathname
                elif private == 2:
                    url_path = '{}{}'.format(
                        site_url,
                        url_for('get_private_file_view',
                                private_file=mini_filename))
                    src_file_pathname = basedir / private_data_dir / pathname
                    dest_file_pathname = basedir / private_data_dir / mini_file_pathname
                else:
                    return False, ''

                if dest_file_pathname.exists():
                    return True, url_path
                else:
                    im = Image.open(src_file_pathname)
                    im.thumbnail(level[size_level])
                    im.save(dest_file_pathname)
                    return True, url_path
            else:
                return False, 'format_not_support'
    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #8
0
def publish_post(data):
    ''' 通过id判断是更新还是创建。  在第一次保存草稿以后,会返回id值,便于第二次保存变为更新 '''
    try:
        title = data['post_title'].strip()
        content = data['post_content']
        code_style = data['code_style'].strip()
        class_id = int(data.get('post_class', 1))
        tags_id = data.get('post_tags', '')
        url = data['post_url'].strip()
        create_time = int(data['post_create_datetime'])
        update_time = int(data['post_update_datetime'])
        summary = data.get('post_summary', '').strip()
        post_id = int(data.get('post_id', 0))

        if len(str(create_time)) > 10:
            create_time = int(str(create_time)[0:10])
        if len(str(update_time)) > 10:
            update_time = int(str(update_time)[0:10])

        if isinstance(tags_id, list):
            tags_id = ','.join(map(str, tags_id))

        write_data = {
            'title': title,
            'posts': content,
            'status': 1,
            'code_style': code_style,
            'class': class_id,
            'tags': tags_id,
            'url': url,
            'create_time': create_time,
            'update_time': update_time,
            'summary': summary,
        }
        if post_id:
            state = g.db.update('posts', write_data, where={'id': post_id})
            # 如果没有更新成功,前端提示注意保存本地
            if state[0] and state[1]:
                return True, ''
            elif state[0] and state[1] == 0:
                return False, 'not_change'
        else:
            timestamp_now = int(datetime.datetime.now().timestamp())
            write_data['id'] = timestamp_now
            state = g.db.insert('posts', write_data)
            if state[0] and state[1]:
                post_id = select('posts',
                                 fields=['id'],
                                 where={'title': title})[0]['id']
                if post_id:
                    return True, {'id': post_id}
    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #9
0
def get_post_index(data):
    try:
        url = data['url']
        if url:
            data = select('posts',
                          fields=[
                              'title', 'create_time', 'update_time', 'posts',
                              'code_style', 'visits'
                          ],
                          where={'url': url})
            data = data[0]
        else:
            data = select('posts',
                          fields=[
                              'title', 'create_time', 'update_time', 'summary',
                              'class', 'visits'
                          ])
            # 需要分页处理, 添加where条件。
            pass
        return True, data
    except Exception:
        log.error(traceback.format_exc())
        return False, ''
Пример #10
0
def check_tagname(tag_name):
    # 返回值, 第二部分为True 表示存在,  False表示不存在
    try:
        if tag_name:
            state = select('tags',
                           fields=['tagname'],
                           where={'tagname': tag_name})
            if state:
                return True, True
            else:
                return True, False
    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #11
0
def check_something(data):
    # check title 与 url是否存在, 已存在返回True,  返回一个字典,{title: True, url: True}
    try:
        title = data['title']
        url = data['url']
        return_data = {}
        if title:
            title = select('posts', fields=['title'], where={'title': title})
            if title:
                return_data['title'] = True
            else:
                return_data['title'] = False

        if url:
            url = select('posts', fields=['url'], where={'url': url})
            if url:
                return_data['url'] = True
            else:
                return_data['url'] = False
        if return_data:
            return True, return_data
    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #12
0
def get_post_list(data):
    try:
        page_num = int(data['page_num'])
        post_num_per_page = int(data['post_num_per_page'])
        offset = (page_num - 1) * post_num_per_page
        search_on = data.get('search_on', False)

        fields = [
            'id', 'title', 'create_time', 'class', 'tags', 'status', 'visits'
        ]
        if search_on is True:
            new_fields = list(map(lambda x: '`{}`'.format(x), fields))
            sql = r'''select {} from `posts` where '''.format(
                ','.join(new_fields))
            keyword = data.get('search_keyword', '').strip()
            post_class = int(data.get('search_class', 0))
            status = int(data.get('search_status', 0))
            search_where = []
            if keyword:
                search_where.append('`posts` like "%{}%"'.format(
                    g.db.conn.escape_string(keyword)))
            if post_class:
                search_where.append('`class` = "{}"'.format(post_class))
            if status:
                search_where.append('`status` = "{}"'.format(status))
            else:
                search_where.append('`status` in (1,2)')
            sql_where = r' and '.join(search_where)
            sql += sql_where
            sql += r' order by `update_time` desc limit {},{};'.format(
                offset, post_num_per_page)
            state = g.db.query(sql)
            if state[0]:
                data = [
                    dict(zip(fields, onedata))
                    for onedata in g.db.cur.fetchall()
                ]
            else:
                return False, ''
        else:
            sql_where = '`status` in (1,2)'
            data = select('posts',
                          fields=fields,
                          where={'status': [1, 2]},
                          sort_field='update_time',
                          limit=post_num_per_page,
                          offset=offset)

        data = handle_post_info(data)
        total_num_sql = r'''select count(id) from `posts` where {}'''.format(
            sql_where)
        # 查询复合条件的有多少条, 作为前端'总条数'的展示数据
        state = g.db.query(total_num_sql)
        if state[0]:
            total_post_num = g.db.cur.fetchone()[0]
        else:
            total_post_num = 0

        return_data = {'list_data': data, 'total_post_num': total_post_num}

        return True, return_data
    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #13
0
def get_attach_list(data):
    try:
        page_num = int(data['page_num'])
        attach_num_per_page = int(data['attach_num_per_page'])
        offset = (page_num - 1) * attach_num_per_page
        search_on = data.get('search_on', False)
        size_level = int(data.get('size_level', 0))

        fields = [
            'id', 'filename', 'is_image', 'pathname', 'mimetype', 'size',
            'width', 'height', 'uptime', 'status', 'private', 'intro'
        ]
        if search_on is True:
            new_fields = list(map(lambda x: '`{}`'.format(x), fields))
            sql = r'''select {} from `attach` where '''.format(
                ','.join(new_fields))
            #            size = int(data.get('size', 0))  # size: 100,   100-200
            #            width = int(data.get('width', 0))
            #            height = int(data.get('height', 0))
            mimetype = data.get('search_mimetype', '').strip()
            private = int(data.get('search_private', 0))
            status = int(data.get('search_status', 1))
            search_where = []
            if mimetype:
                search_where.append('`mimetype` = "{}"'.format(
                    g.db.conn.escape_string(mimetype)))
            if private:
                search_where.append('`private` = "{}"'.format(private))
            if status:
                search_where.append('`status` = "{}"'.format(status))
            else:
                search_where.append('`status` = "1"')
            sql_where = r' and '.join(search_where)
            sql += sql_where
            sql += r' order by `uptime` desc limit {},{};'.format(
                offset, attach_num_per_page)
            state = g.db.query(sql)
            if state[0]:
                data = [
                    dict(zip(fields, onedata))
                    for onedata in g.db.cur.fetchall()
                ]
            else:
                return False, ''
        else:
            sql_where = '`status` = 1'
            data = select('attach',
                          fields=fields,
                          where={'status': 1},
                          sort_field='uptime',
                          limit=attach_num_per_page,
                          offset=offset)

        total_num_sql = r'''select count(id) from `attach` where {}'''.format(
            sql_where)
        # 查询复合条件的有多少条, 作为前端'总条数'的展示数据
        state = g.db.query(total_num_sql)
        if state[0]:
            total_attach_num = g.db.cur.fetchone()[0]
        else:
            total_attach_num = 0

        # 添加文件下载地址
        for file_data in data:
            if file_data['private'] == 1:
                file_data['url'] = '{}/{}'.format(site_url,
                                                  file_data['pathname'])
            elif file_data['private'] == 2:
                file_data['url'] = '{}{}'.format(
                    site_url,
                    url_for('get_private_file_view',
                            private_file=file_data['filename']))
            else:
                return False, ''
            del file_data['pathname']

            # 添加缩略图下载地址
            if size_level:
                state, url = make_mini_photo(file_data['filename'], size_level)
                if state:
                    file_data['mini_url'] = url
                else:
                    file_data['mini_url'] = False

        return_data = {'list_data': data, 'total_attach_num': total_attach_num}

        return True, return_data
    except Exception:
        log.error(traceback.format_exc())
    return False, ''
Пример #14
0
def delete_attach(data):
    '''删除附件'''
    try:
        filename = data.get('file_name', '').strip()
        file_id = int(data.get('file_id', 0))
        file_info = select('attach',
                           fields=['pathname', 'private', 'status'],
                           where={
                               'filename': filename,
                               'id': file_id
                           })[0]
        if file_info:
            pathname = file_info['pathname']
            private = file_info['private']
            status = file_info['status']
            if status == 1:
                dest_file_pathname = pathname
            elif status == 2:
                only_filename, ext_name = filename.split('.')
                dest_filename = '{}_{}.{}'.format(only_filename, 'invalid',
                                                  ext_name)
                dest_file_pathname = os.path.dirname(pathname) + '/{}'.format(
                    dest_filename)
            else:
                log.error(
                    'fund:delete_attach|status:{}|status is error'.format(
                        status))
                return False, ''

            if private == 1:
                sys_file_pathname = basedir / dest_file_pathname
            elif private == 2:
                sys_file_pathname = basedir / private_data_dir / dest_file_pathname
            else:
                log.error(
                    'fund:delete_attach|private:{}|private is error'.format(
                        private))
                return False, ''
            try:
                g.db.begin()
                state = g.db.delete('attach',
                                    where={
                                        'filename': filename,
                                        'id': file_id
                                    })
                if state[0] and state[1] == 1:
                    os.remove(sys_file_pathname)
                    g.db.commit()
                    delete_mini_photo(pathname, private)
                    return True, ''
                else:
                    g.db.rollback()
                    log.error(
                        'fund:delete_attach|state:{}|db exec state is error'.
                        format(state))
            except Exception:
                log.error(traceback.format_exc())
                g.db.rollback()
    except Exception:
        log.error(traceback.format_exc())
    return False, ''