Exemplo n.º 1
0
def manage_topic(**kwargs):
    """用户对话题的管理"""
    message = {"message": "success"}
    try:
        the_type = kwargs.pop("the_type")
        if the_type == "add":
            """添加"""
            if kwargs['begin_date'] == "":
                kwargs['begin_date'] = my_db.current_datetime()
            if kwargs['end_date'] == "":
                kwargs['end_date'] = my_db.current_datetime(365)
            kwargs['can_show'] = 0
            sql = my_db.structure_sql("add", "topic_info", **kwargs)
            sql_session = my_db.sql_session()
            print(sql)
            sql_session.execute(sql)
            sql_session.commit()
            sql_session.close()

        elif the_type == "edit":
            pass
    except KeyError:
        message['message'] = "不理解的操作"
    except Exception as e:
        message['message'] = "数据库执行错误"
        print(e)
    finally:
        return message
Exemplo n.º 2
0
def vote(**kwargs):
    """投票计数"""
    message = {"message": "success"}
    kwargs['create_date'] = my_db.current_datetime()
    sql = my_db.structure_sql("add", "vote_count", **kwargs)
    sql_session = my_db.sql_session()
    try:
        sql_session.execute(sql)
        sql_session.commit()
        """同步道缓存"""
        lock = RLock()
        lock.acquire()
        add_vote_cache(kwargs['topic_id'], kwargs['support_a'],
                       kwargs['support_b'])
        lock.release()
    except sqlalchemy.exc.IntegrityError as e1:
        """
        re.findall(r"for key '(.+?)'",str) 是从str中找到匹配以for key 'PRIMARY'")
        句子中的PRIMARY,findall方法返回的是数组
        """
        print(e1.args)
        error_cause = re.findall(r"for key '(.+?)'", e1.args[-1])[0]
        if error_cause == "only_once":
            message["message"] = "你已经投过票了"
        else:
            print(error_cause)
            message['message'] = "投票失败,请联系管理员"
    finally:
        sql_session.close()
    return message
Exemplo n.º 3
0
def up_down(**kwargs):
    """赞和踩"""
    message = {"message": "success"}
    up_down_str = kwargs.get("up_down_str")
    if up_down_str is None:
        message['message'] = 'error'
    else:
        kwargs.pop("up_down_str")
        if up_down_str == "up":
            kwargs['up_it'] = 1
            kwargs['down_it'] = 0
        else:
            kwargs['up_it'] = 0
            kwargs['down_it'] = 1
        kwargs['create_date'] = my_db.current_datetime()
        ses = my_db.sql_session()
        comment_id = kwargs['comment_id']
        only_id= kwargs['only_id']
        sql = "delete from up_down_info where comment_id={} and only_id='{}'".format(comment_id, only_id)
        ses.execute(sql)
        ses.commit()
        sql = my_db.structure_sql("add", "up_down_info", **kwargs)
        ses.execute(sql)
        ses.commit()
        ses.close()
    return message
Exemplo n.º 4
0
def index_topic_list():
    """获取首页的各频道的话题列表,返回的是是字典
    字典以channel_id为key,值是话题字典的数组,排序以优先级+发布时间来排序
    这里不包含置顶帖子,置顶帖子会在视图函数中与此结果重新组合。
    """
    cache = my_db.cache
    key = "index_topic_dict"
    index_topic_dict = cache.get(key)
    if index_topic_dict is None:
        """从数据库查询"""
        channel_id_list = [x['channel_id'] for x in channel_list()]
        current_date = my_db.current_datetime()
        index_topic_dict = dict()  # 结果集容器
        columns_str = "channel_id,class_id,top_id,top_title"
        columns = columns_str.split(",")
        columns.append('view_count')
        ses = my_db.sql_session()
        for channel_id in channel_id_list:
            """首页查询的结果将不会排除过期的话题/投票"""
            sql = "select {0},(select count(view_count.view_id) from view_count where " \
                  "topic_info.top_id=view_count.topic_id) from topic_info where can_show=1 " \
                  "and channel_id={1} " \
                  "order by create_date desc limit 0,5".format(columns_str, channel_id)
            proxy = ses.execute(sql)
            temp = proxy.fetchall()
            result = [dict(zip(columns, x)) for x in temp]
            index_topic_dict[channel_id] = result
        ses.close()
        """将字典按照左右两列排序,以帖子被浏览总数降序排列"""
        pass
        cache.set(key, index_topic_dict, timeout=60 * 1)

    return index_topic_dict
Exemplo n.º 5
0
def add(user_id, detail):
    """对某个用户添加一个新的消息通知。
    当遇到评论过千、审核通过时,调用此方法将消息写入数据库。
    detail为通知的详细内容。"""
    session = my_db.sql_session()
    sql = "insert into zvoter.notification (`user_id`, `detail`, `read`, `date`) values ('{}', '{}', {}, '{}')".\
        format(user_id, detail, 0, my_db.current_datetime())
    session.execute(sql)
    session.commit()
Exemplo n.º 6
0
def __add_view_count(topic_id, only_id, from_ip, browser_type):
    """低级方法。对页面浏览进行计数"""
    message = {'message': "success"}
    sql = "insert into view_count(topic_id,only_id,from_ip,browser_type,create_date) " \
          "values('{0}','{1}','{2}','{3}','{4}')".format(topic_id, only_id, from_ip,
                                                         browser_type, my_db.current_datetime())
    ses = my_db.sql_session()
    ses.execute(sql)
    ses.commit()
    ses.close()
    return message
Exemplo n.º 7
0
def manage_comment(**kwargs):
    """管理用户留言"""
    message = {"message": "success"}
    ses = my_db.sql_session()
    try:
        the_type = kwargs.pop("the_type")
        if the_type == "add":
            """添加留言"""
            kwargs['create_date'] = my_db.current_datetime()
            sql = my_db.structure_sql("add", "comment_info", **kwargs)
            ses.execute(sql)
            ses.commit()
        elif the_type == "edit":
            comment_id = kwargs.pop("comment_id")
            sql = my_db.structure_sql("edit", "comment_info",
                                      "where comment_id={}".format(comment_id),
                                      **kwargs)
            ses.execute(sql)
            ses.commit()
        elif the_type == 'delete':
            comment_id = kwargs.pop("comment_id")
            sql = my_db.structure_sql("delete", "comment_info",
                                      "where comment_id={}".format(comment_id),
                                      **kwargs)
            ses.execute(sql)
            ses.commit()
        elif the_type == "by_comment_id":
            """根据评论id获取话题"""
            comment_id = kwargs.pop("comment_id")
            child_sql = "(SELECT CONCAT_WS(' vs ',SUM(up_it),SUM(down))  " \
                        "FROM up_down_info WHERE up_down_info.comment_id=comment_info.comment_id)"  # 查询赞和踩的子查询
            column_str = "comment_id,comment_text,comment_author,user_info.user_nickname,user_info.user_img_url," \
                         "create_date,support_side,topic_id,parent_comment,comment_status,{}".format(child_sql)
            sql = "select {} from comment_info,user_info where comment_status>0  user_id=comment_author " \
                  "and comment_id={}".format(column_str, comment_id)
            proxy = ses.execute(sql)
            result = proxy.fetchone()
            columns = [
                'comment_id', 'comment_text', 'user_id', 'user_nickname',
                'user_img_url', 'create_date', 'support_side', 'topic_id',
                'parent_comment', 'comment_status', "up_vs_down"
            ]
            """
            列名分别代表:评论id,评论内容,用户id,用户昵称,用户头像,发布时间,支持方向,话题id,评论状态
            被评论对象id,赞和踩的数量
            """
            if result is None:
                message['data'] = dict()
            else:
                message['data'] = dict(zip(columns, result))
        elif the_type == "by_topic_id":
            """根据话题id获取话题"""
            topic_id = kwargs.pop("topic_id")
            child_sql = "(SELECT CONCAT_WS(' vs ',SUM(up_it),SUM(down_it))  " \
                        "FROM up_down_info WHERE up_down_info.comment_id=comment_info.comment_id)"  # 查询赞和踩的子查询
            column_str = "comment_id,comment_text,comment_author,user_info.user_nickname,user_info.user_img_url," \
                         "comment_info.create_date,support_side,topic_id,parent_comment,comment_status,{}".\
                format(child_sql)
            sql = "select {} from comment_info,user_info where comment_status>0 and  user_id=comment_author " \
                  "and topic_id={}".format(column_str, topic_id)
            proxy = ses.execute(sql)
            result = proxy.fetchall()
            columns = [
                'comment_id', 'comment_text', 'user_id', 'user_nickname',
                'user_img_url', 'create_date', 'support_side', 'topic_id',
                'parent_comment', 'comment_status', "up_vs_down"
            ]
            """
            列名分别代表:评论id,评论内容,用户id,用户昵称,用户头像,发布时间,支持方向,话题id,评论状态
            被评论对象id,赞和踩的数量
            """
            if len(result) == 0:
                message['data'] = list()
            else:
                result = [dict(zip(columns, x)) for x in result]
                message['data'] = result
        elif the_type == "all":
            """获取所有评论,用于后台管理"""
            topic_id = kwargs.pop("topic_id")
            child_sql = "(SELECT CONCAT_WS(' vs ',SUM(up_it),SUM(down))  " \
                        "FROM up_down_info WHERE up_down_info.comment_id=comment_info.comment_id)"  # 查询赞和踩的子查询
            column_str = "comment_id,comment_text,comment_author,user_info.user_nickname,user_info.user_img_url," \
                         "create_date,support_side,topic_id,parent_comment,comment_status,{}".format(child_sql)
            sql = "select {} from comment_info,user_info where user_id=comment_author " \
                  "and topic_id={}".format(column_str, topic_id)
            proxy = ses.execute(sql)
            result = proxy.fetchall()
            columns = [
                'comment_id', 'comment_text', 'user_id', 'user_nickname',
                'user_img_url', 'create_date', 'support_side', 'topic_id',
                'parent_comment', 'comment_status', "up_vs_down"
            ]
            """
            列名分别代表:评论id,评论内容,用户id,用户昵称,用户头像,发布时间,支持方向,话题id,评论状态
            被评论对象id,赞和踩的数量
            """
            if len(result) == 0:
                message['data'] = list()
            else:
                message['data'] = [dict(zip(columns, x)) for x in result]
        elif the_type == "page":
            """分页查询所有评论"""
            index = kwargs.get("index")
            length = kwargs.get("page_length")
            try:
                index = int(index)
                length = int(length)
                columns = [
                    'comment_id', 'comment_text', 'comment_author',
                    'comment_info.create_date', 'support_side',
                    'user_info.user_nickname', 'topic_id',
                    'topic_info.top_title', 'parent_comment', 'comment_status'
                ]
                sql = "select " + ",".join(columns) + (
                    " from comment_info,user_info,topic_info where "
                    "topic_info.top_id=comment_info.topic_id and "
                    "user_id=comment_author order by create_date desc "
                    "limit {},{}".format((index - 1) * length, length))
                try:
                    columns = [
                        'comment_id', 'comment_text', 'comment_author',
                        'create_date', 'support_side', 'user_nickname',
                        'topic_id', 'topic_title', 'parent_comment',
                        'comment_status'
                    ]
                    proxy_result = ses.execute(sql)
                    result = proxy_result.fetchall()
                    if len(result) != 0:
                        result = [my_db.str_format(x) for x in result]
                        data = [dict(zip(columns, x)) for x in result]
                    else:
                        data = []
                    message['data'] = data
                except Exception as e:
                    print(e)
                    message['message'] = "查询错误"
            except ValueError:
                message['message'] = "无效的页码或者步长"

    except KeyError:
        message['message'] = "不理解的操作"
    except Exception as e:
        print(e)
        message['message'] = "数据库执行错误"
    finally:
        ses.close()
        return message
Exemplo n.º 8
0
def manage_topic_admin(**kwargs):
    """后台对话题的管理"""
    message = {"message": "success"}
    sql_session = my_db.sql_session()
    try:
        the_type = kwargs.pop("the_type")
        if the_type == "add":
            """添加"""
            if kwargs['begin_date'] == "":
                kwargs['begin_date'] = my_db.current_datetime()
            if kwargs['end_date'] == "":
                kwargs.pop('end_date')
            kwargs['can_show'] = 0
            sql = my_db.structure_sql("add", "topic_info", **kwargs)
            print(sql)
            sql_session.execute(sql)
            sql_session.commit()

        elif the_type == "edit":
            """编辑"""
            try:
                top_id = kwargs.pop("top_id")
                if kwargs['begin_date'] == "":
                    kwargs['begin_date'] = my_db.current_datetime()
                if kwargs['end_date'] == "":
                    kwargs['end_date'] = my_db.current_datetime(365)
                sql = my_db.structure_sql("edit", "topic_info",
                                          "where top_id='{}'".format(top_id),
                                          **kwargs)
                sql_session.execute(sql)
                sql_session.commit()
            except KeyError:
                message['message'] == '错误的话题id'
            except Exception as e:
                message['message'] = "数据库执行错误"
                print(e)

        elif the_type == "drop":
            """删除"""
            try:
                top_id = kwargs.pop("top_id")
                sql = "delete from topic_info where top_id={}".format(top_id)
                sql_session.execute(sql)
                sql_session.commit()
            except KeyError:
                message['message'] == '错误的话题id'
            except Exception as e:
                message['message'] = "数据库执行错误"
                print(e)

        elif the_type == "status":
            """话题状态的调整,审核/拒绝/置顶等"""
            try:
                top_id = kwargs.pop("top_id")
                topic_status = kwargs.pop("topic_status")
                sql = "update topic_info set can_show={} where top_id={}".format(
                    topic_status, top_id)
                sql_session.execute(sql)
                sql_session.commit()
            except KeyError:
                message['message'] = '错误的话题id'
            except Exception as e:
                print(e)
                message['message'] = "数据库执行错误"

        elif the_type == "single":
            """根据id获取单个话题的内容"""
            top_id = kwargs.pop("top_id")

            child_sql = "(SELECT CONCAT_WS(' vs ',SUM(support_a),SUM(support_b))  " \
                        "FROM vote_count WHERE vote_count.topic_id=topic_info.top_id)"  # 查询ab支持度的子查询
            sql = "SELECT top_id,top_title,top_content,viewpoint_a,viewpoint_b,can_show,img_url_a,img_url_b," \
                  "topic_info.channel_id,channel_info.channel_name,topic_info.class_id," \
                  "class_info.class_name,end_date,begin_date," \
                  "user_info.user_nickname,{} FROM topic_info,channel_info,class_info,user_info " \
                  "WHERE user_info.user_id=topic_info.author " \
                  "AND channel_info.channel_id=topic_info.channel_id and " \
                  "class_info.class_id=topic_info.class_id AND  " \
                  "top_id='{}'".format(child_sql, top_id)
            columns = [
                'top_id', 'top_title', 'top_content', 'viewpoint_a',
                'viewpoint_b', 'can_show', 'img_url_a', 'img_url_b',
                'channel_id', 'channel_name', 'class_id', 'class_name',
                'end_date', 'begin_date', 'author', "a_vs_b"
            ]
            proxy_result = sql_session.execute(sql)
            result = proxy_result.fetchone()
            result = my_db.str_format(result)
            sql_session.close()
            data = dict(zip(columns, result))
            message['data'] = data

        elif the_type == "page":
            """分页查询话题"""
            index = kwargs.get("index")
            length = kwargs.get("page_length")
            try:
                index = int(index)
                length = int(length)
                columns = get_columns()
                sql = "select " + ",".join(columns) + (
                    " from topic_info order by create_date desc "
                    "limit {},{}".format((index - 1) * length, length))
                try:
                    proxy_result = sql_session.execute(sql)
                    result = proxy_result.fetchall()
                    if len(result) != 0:
                        result = [my_db.str_format(x) for x in result]
                        data = [dict(zip(columns, x)) for x in result]
                    else:
                        data = []
                    message['data'] = data
                except Exception as e:
                    print(e)
                    message['message'] = "查询错误"
            except ValueError:
                message['message'] = "无效的页码或者步长"

    except KeyError as e:
        print(e)
        message['message'] = "不理解的操作"
    except Exception as e:
        print(e)
        message['message'] = "数据库执行错误"
    finally:
        sql_session.close()
        return message