コード例 #1
0
    def getActivities(self, uid, page=1, limit=15):
        if not uid:
            return None
        user_act_list = self.queryMany(filterString=[('uid', uid), ('status', 1)], limit=limit, pageNo=page)
        ids = []
        for item in user_act_list:
            ids.append(item['activity_id'])

        ids = set(ids)
        act = GroupActivity()
        act_list = act.getGroupActivityListById(ids)
        if not act_list:
            return []

        res = []
        #获取组织活动的发起人
        group_leader_ids = []
        for item in user_act_list:
            if act_list.has_key(item['activity_id']):
                group_leader_ids.append(act_list[item['activity_id']]['group_leader'])

        user = User()
        user_list = user.getUsersByUids(group_leader_ids)

        for item in user_act_list:
            if act_list.has_key(item['activity_id']):
                item['activity_info'] = act_list[item['activity_id']]
                item['activity_info']['create_time'] = item['activity_info']['create_time'].strftime("%Y/%m/%d %H:%M:%S")
                item['activity_info']['dead_time'] = item['activity_info']['dead_time'].strftime("%Y/%m/%d %H:%M:%S")
                item['activity_info']['group_leader_name'] = user_list[act_list[item['activity_id']]['group_leader']]['user_name']
                res.append(item)
        return res
コード例 #2
0
    def post(self):
        user_info = self.get_current_user()
        if not user_info:
            self.return_json({'msg': ErrorMessage.error_message['037'], 'code': 'error', 'num': '037', 'is_need_cpatcha': 0}, finish=True)
            return

        uid = str(user_info['id'])

        pid = self.get_argument('pid', 0)
        ancestor_id = self.get_argument('ancestor_id', 0)
        comment = filterTags(self.get_argument('comment', ''))
        feedback_id = self.get_argument('feedback_id', 0)

        if not comment:
            self.return_json({'msg': ErrorMessage.error_message['035'], 'code': 'error', 'num': '035'}, finish=True)
            return
        if not feedback_id:
            self.return_json({'msg': ErrorMessage.error_message['036'], 'code': 'error', 'num': '036'}, finish=True)
            return

        #频率控制
        tmp = delayPostLimit('feedback-reply', uid, 0.5)
        if not tmp:
            self.return_json({'msg': ErrorMessage.error_message['043'], 'code': 'error', 'num': '043'}, finish=True)
            return

        #查询评论的信息
        comment_info = self.f_c.getItem(pid)
        if not comment_info:
            self.return_json({'msg': ErrorMessage.error_message['036'], 'code': 'error', 'num': '036'}, finish=True)
            return

        create_timestamp = time.time()
        create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(create_timestamp))

        res, new_comment = self.f_c.addComment(self.settings, uid, pid, ancestor_id, comment, feedback_id, create_time, comment_info['uid'], type='feedback_comment')
        if not res:
            self.return_json({'msg': ErrorMessage.error_message['038'], 'code': 'error', 'num': '038'}, finish=True)
            return
        #获取被评论的用户姓名
        user = User()
        to_user_info = user.getItem(comment_info['uid'])
        res_data = {
            'fcid': res,
            'user_name': user_info['user_name'],
            'create_time': utiles.timeBefore(create_time),
            'avatar': user_info['avatar'],
            'uid': user_info['id'],
            'comment': new_comment,
            'p_comment_id': pid,
            'to_user_id': comment_info['uid'],
            'to_user_name': to_user_info['user_name'] if to_user_info else ''
        }
        self.return_json({'code': 'success', 'msg': SuccessMessage.success_message['006'], 'res': res_data}, finish=True)
        return
コード例 #3
0
 def get_current_user(self, info=True):
     uid = self.get_secure_cookie("uid")
     if not uid:
         return None
     if info:
         user = User()
         user_info = user.getItem(uid)
         user_info['avatar'] = '/avatar/'+user_info['avatar']
         return user_info
     else:
         return uid
コード例 #4
0
 def post(self):
     val = self.get_argument('val', '')
     type = self.get_argument('type', '')
     user = User()
     if user.checkUserOrEmail(val, type) == False:
         ret = {'msg': '', 'code': 'success'}
     else:
         ret = {
             'msg':
             ErrorMessage.error_message['012' if type ==
                                        'email' else '011'],
             'code':
             'error'
         }
     self.return_json(ret)
コード例 #5
0
 def checkTokenUrl(self, uid):
     ret = {'code': 'success', 'is_send': True}
     ret_017 = {
         'msg': ErrorMessage.error_message['017'],
         'code': 'error',
         'num': '017',
         'is_send': False
     }
     ret_016 = {
         'msg': ErrorMessage.error_message['016'],
         'code': 'error',
         'num': '016',
         'is_send': True
     }
     ret_019 = {
         'msg': ErrorMessage.error_message['019'],
         'code': 'error',
         'num': '019',
         'is_send': False
     }
     ret_022 = {
         'msg': ErrorMessage.error_message['022'],
         'code': 'error',
         'num': '022',
         'is_send': False
     }
     u = User()
     u_info = u.getItem(uid)
     if not u_info:
         return ret_022
     else:
         if u_info['is_verify'] == 0:
             return ret_016
         else:
             return ret
     #获取用户验证信息
     uv = UserVerify()
     uv_info = uv.getVerifyInfo(uid)
     if not uv_info:
         return ret_017
     if utiles.formateDateToTimestamp(uv_info['verify_expire_time']) < int(
             time.mktime(datetime.datetime.now().timetuple())):
         return ret_019
     #需要发送邮件 code=error不需要发送邮件
     return ret
コード例 #6
0
def verifyIsRemember(self, token, token_time):
    fp = self.get_argument('fp', '')
    ec = MyCrypt(options.login_key)
    token = eval(ec.decrypt(token))
    token_time = ec.decrypt(token_time)
    ip = self.request.remote_ip
    if (token.has_key('fp') and token['fp']==fp) and (token.has_key('date') and token['date']==token_time) and (token.has_key('ip') and token['ip']==ip):
        if token.has_key('salt') and token.has_key('uid'):
            #通过uid查询salt是否相等
            user = User()
            info = user.queryOne([('uid', token['uid'])], ['salt'])
            if token['salt']==info['salt']:
                self.set_secure_cookie("uid", str(info.id),
                                   #domain=options.cookie_domain,
                                   #httponly=True,
                                   #secure=True,
                                   #expires_days=None,
                                   expires=options.remember_time_out+token_time)
                return True
    return False
コード例 #7
0
 def wrapper(self, *args, **kwargs):
     uid = self.get_secure_cookie('uid')
     if not uid:
         self.write(
             json.dumps({
                 'code': 'error',
                 'msg': ErrorMessage.error_message['019'],
                 'num': '019'
             }))
         self.finish()
     user = User()
     info = user.getItem(uid)
     if info['is_verify'] == 1:
         self.write(
             json.dumps({
                 'code': 'error',
                 'msg': ErrorMessage.error_message['018'],
                 'num': '018'
             }))
         self.finish()
     return method(self, *args, **kwargs)
コード例 #8
0
    def get(self, *args, **kwargs):
        token = self.get_argument('token', None)
        if token:
            now = int(time.mktime(datetime.datetime.now().timetuple()))
            ec = MyCrypt(options.login_key)
            decrpt_data = ec.decrypt(token)
            decrpt_data = decrpt_data.split('|')

            #修改用户的验证标识
            uv = UserVerify()
            uv_info = uv.queryOne(filterString=[('token', decrpt_data[0])])
            if not uv_info:
                self._context.error = ErrorMessage.error_message['025']
            else:
                if uv_info['uid'] != decrpt_data[1]:
                    self._context.error = ErrorMessage.error_message['025']
                elif utiles.formateDateToTimestamp(
                        uv_info['verify_expire_time']) < now:
                    self._context.error = ErrorMessage.error_message['026']
                else:
                    user = User()
                    u_info = user.queryOne(filterString=[('id',
                                                          decrpt_data[1])])
                    if u_info['user_email'] != decrpt_data[2]:
                        self._context.error = ErrorMessage.error_message['025']
                    else:
                        if u_info['is_verify'] == 1:
                            self._context.error = ErrorMessage.error_message[
                                '027']
                        user.updateInfo(filterString=[('is_verify', 1)],
                                        where=[('id', decrpt_data[1])])
                        #修改用户总数
                        config = SysConfig()
                        config.incConfig('user_total')
                        self._context.msg = SuccessMessage.success_message[
                            '005']
        else:
            self._context.error = ErrorMessage.error_message['025']
        self.render('./msg.html')
コード例 #9
0
ファイル: chat.py プロジェクト: mrvegazhou/pySkeleton
 def post(self):
     to_user_id = self.get_argument('to_user_id', None)
     if not to_user_id:
         self.finish({
             'code': 'error',
             'msg': ErrorMessage.error_message['048']
         })
         return
     chat_user_info = User.getItem(to_user_id)
     if not chat_user_info:
         self.finish({
             'code': 'error',
             'msg': ErrorMessage.error_message['049']
         })
         return
     self_user_info = self.get_current_user(info=True)
     chat_user = self.get_chat_user_info(chat_user_info)
     self_user = self.get_chat_user_info(self_user_info)
     room_id = get_key(chat_user_info['id'], self_user_info['id'])
     res = yield gen.Task(redis_backend.UserManager.del_chat_user,
                          self_user, chat_user, room_id)
     self.finish({'code': 'success', 'msg': res})
     return
コード例 #10
0
class LoginHandler(BaseHandler):
    user = User()

    def get(self):
        self._context.next = self.get_next_url()
        self._context.title = self._locale.translate('login_name').encode(
            "utf-8")
        self.render("user/login.html", url_escape=escape.url_escape)

    def post(self):
        ip = self.request.remote_ip
        user_password = self.get_argument('user_password', None)
        user_email = self.get_argument('user_email', None)
        info = self.user.login(user_email)

        if info:
            hash = hashlib.md5()
            hash.update(str(info['salt']) + str(user_password))
            if info['pass_word'] != hash.hexdigest():
                ret = {
                    'msg': ErrorMessage.error_message['004'],
                    'code': 'error'
                }
                self.finish(self.write(json_encode(ret)))
            #当前时间戳
            now = time.time()
            if info['user_ip'] != ip:
                self.user.updateInfo(
                    [('user_ip', ip),
                     ('login_time', utiles.timestampToDate(now))],
                    [('id', info.id)])
            else:
                #更新登录时间
                self.user.updateInfo(
                    [('login_time', utiles.timestampToDate(now))],
                    [('id', info.id)])
            self.set_secure_cookie("uid",
                                   str(info.id),
                                   expires=time.time() + options.reg_time_out)
            #判断记住帐号
            remember = self.get_argument('remember', '')
            if remember == 1:
                #加密免登录
                fp = self.get_argument('fp', '')
                ec = MyCrypt(options.login_key)
                data = '{"fp": %s, "date": %s, "salt": %s, "ip": %s, "uid": %s}' % (
                    fp, now, info['salt'], ip, info.id)
                self.set_secure_cookie('token',
                                       str(ec.encrypt(data)),
                                       expires=now + options.remember_time_out)
                self.set_secure_cookie('token_time',
                                       str(ec.encrypt(now)),
                                       expires=now + options.remember_time_out)
            ret = {
                'msg': SuccessMessage.success_message['001'],
                'code': 'success',
                'res': info,
                'next': self.get_next_url()
            }
            self.finish(self.write(self.json_encode(ret)))
        else:
            ret = {'msg': ErrorMessage.error_message['003'], 'code': 'error'}
            self.finish(self.write(json_encode(ret)))
コード例 #11
0
class RegHandler(BaseHandler):

    d = CommonDistrict()

    #地区赋值
    def assignDirection(self):
        items = self.d.getDistrict(0)
        self._context.district = items

    #生成密码
    def generatePwd(self, reg_password, salt):
        hash = hashlib.md5()
        hash.update(salt + str(reg_password))
        return hash.hexdigest()

    #到邮箱验证用户注册url
    def checkTokenUrl(self, uid):
        ret = {'code': 'success', 'is_send': True}
        ret_017 = {
            'msg': ErrorMessage.error_message['017'],
            'code': 'error',
            'num': '017',
            'is_send': False
        }
        ret_016 = {
            'msg': ErrorMessage.error_message['016'],
            'code': 'error',
            'num': '016',
            'is_send': True
        }
        ret_019 = {
            'msg': ErrorMessage.error_message['019'],
            'code': 'error',
            'num': '019',
            'is_send': False
        }
        ret_022 = {
            'msg': ErrorMessage.error_message['022'],
            'code': 'error',
            'num': '022',
            'is_send': False
        }
        u = User()
        u_info = u.getItem(uid)
        if not u_info:
            return ret_022
        else:
            if u_info['is_verify'] == 0:
                return ret_016
            else:
                return ret
        #获取用户验证信息
        uv = UserVerify()
        uv_info = uv.getVerifyInfo(uid)
        if not uv_info:
            return ret_017
        if utiles.formateDateToTimestamp(uv_info['verify_expire_time']) < int(
                time.mktime(datetime.datetime.now().timetuple())):
            return ret_019
        #需要发送邮件 code=error不需要发送邮件
        return ret

    #保存推荐的朋友和活动信息
    def saveRecommend(self):
        rec_friends = self.get_argument('rec_friends', None)
        rec_activities = self.get_argument('rec_activities', None)

    #生成头像
    def generateAvatar(self, email):
        if not email:
            return False
        identicon_png = genarateAvatar(email)
        now = datetime.datetime.now()
        #存储头像的路径
        avatar_url = self.settings[
            'uploads_path'] + os.path.sep + 'avatar' + os.path.sep + now.year + '-' + utiles.dateRange(
                now.month)
        if not os.path.isdir(avatar_url):
            os.makedirs(avatar_url)
        avatar_img_name = hashlib.sha256(str(uuid.uuid4())) + '_' + str(
            int(time.time())) + '.png'
        avatar = avatar_url + os.path.sep + avatar_img_name
        with open(avatar, 'wb') as f:
            f.write(identicon_png)
        return now.year + '-' + utiles.dateRange(
            now.month) + os.path.sep + avatar_img_name

    _handler_template = "user/reg.html"

    user = User()

    @gen.coroutine
    @asynchronous
    def post(self):
        update = int(self.get_argument('reg_update', 0))
        next_step = self.get_argument("next_step", 1)
        # 防止穷举
        yield gen.Task(IOLoop.instance().add_timeout, time.time() + 2)
        error = []
        #获取用户uid
        uid = self.get_secure_cookie('uid', None)
        if next_step == '1':
            item = {}
            reg_email = self.get_argument("reg_email", '')
            reg_password = self.get_argument("reg_password", '')
            reg_again_password = self.get_argument("reg_again_password", '')
            reg_agree = self.get_argument("reg_agree", '')
            reg_area = self.get_argument('h_reg_area', '')
            reg_gender = self.get_argument('reg_gender', 0)
            reg_user_name = self.get_argument('reg_user_name', '')
            salt = str(utiles.generate_randsalt(size=5))

            if update == '1':
                #当uid失效 页面进入注册空页面
                if not uid:
                    self.assignDirection()
                    self._handler_template = 'user/reg.html'
                    self._context.next = self.get_next_url()
                    self._context.error = []
                    self.render(self._handler_template)
                    return
                if reg_email:
                    if not utiles.validateEmail(reg_email):
                        error.append(ErrorMessage.error_message['005'])
                    else:
                        item['user_email'] = reg_email
                if reg_password and reg_again_password:
                    if len(reg_password) < 6:
                        error.append(ErrorMessage.error_message['006'])
                    elif reg_password != reg_again_password:
                        error.append(ErrorMessage.error_message['007'])
                    else:
                        item['pass_word'] = self.generatePwd(
                            reg_password, salt)
                #判断邮箱和用户名是否重复
                if self.user.checkUserOrEmail(reg_email, 'email', uid):
                    error.append(ErrorMessage.error_message['011'])
                if self.user.checkUserOrEmail(reg_user_name, '', uid):
                    error.append(ErrorMessage.error_message['012'])

                if reg_gender:
                    item['gender'] = reg_gender
                if reg_area:
                    item['area_id'] = reg_area
                if reg_user_name:
                    item['user_name'] = reg_user_name
                item['salt'] = salt
                item['id'] = uid
            else:
                #判断用户名是否重复
                if self.user.checkUserOrEmail(reg_user_name):
                    error.append(ErrorMessage.error_message['012'])
                #判断用户邮箱是否重复
                if self.user.checkUserOrEmail(reg_email, 'email'):
                    error.append(ErrorMessage.error_message['011'])
                if not utiles.validateEmail(reg_email):
                    error.append(ErrorMessage.error_message['005'])
                if len(reg_password) < 6:
                    error.append(ErrorMessage.error_message['006'])
                if reg_password != reg_again_password:
                    error.append(ErrorMessage.error_message['007'])
                if not reg_agree:
                    error.append(ErrorMessage.error_message['008'])
                if not reg_area:
                    error.append(ErrorMessage.error_message['009'])
                if not reg_gender:
                    error.append(ErrorMessage.error_message['013'])

            if error:
                self.assignDirection()
                self._context.error = ','.join(error)
                self._handler_template = 'user/reg.html'
                self._context.next = self.get_next_url()
                if uid:
                    user_info = self.user.getItem(uid)
                    self._context.user_info = user_info
                    self._context.area = ','.join(
                        self.d.getDistrictParents(user_info['area_id'],
                                                  res=[]))
                self.render(self._handler_template)
                return

            #保存注册信息
            ip = self.request.remote_ip
            now = time.time()
            #修改用户注册信息
            if update == 1:
                if not item:
                    self.redirect("/reg/?step=1")
                    return
                count = self.user.updateItem(item)
                if count == 0:
                    self.assignDirection()
                    self._context.error = ErrorMessage.error_message['014']
                    self._handler_template = 'user/reg.html'
                    self.render(self._handler_template)
                res = uid
            else:
                avatar = self.generateAvatar(reg_email)
                res = self.user.addItem(
                    item={
                        'area_id': reg_area,
                        'user_name': reg_user_name if reg_user_name else '',
                        'user_email': reg_email,
                        'pass_word': self.generatePwd(reg_password, salt),
                        'user_ip': ip,
                        'salt': salt,
                        'gender': reg_gender,
                        'create_time': utiles.timestampToDate(now),
                        'avatar': avatar
                    })
            if res:
                self.set_secure_cookie("uid",
                                       str(res),
                                       expires=time.time() +
                                       options.reg_time_out)
                self.redirect("/reg/?step=1")
            else:
                self.assignDirection()
                self._context.error = ErrorMessage.error_message['010']
                self._handler_template = "user/reg.html"
            self.render(self._handler_template)
            self.finish()
        elif next_step == '2':
            #获取用户验证信息
            ret = self.checkTokenUrl(uid)
            if ret['code'] == 'error':
                if uid:
                    #获取用户信息
                    user_info = self.user.getItem(uid)
                    self._context.user_info = user_info
                    self._context.user_email = user_info['user_email']
                self._context.error = ret['msg']
                self._context.is_send = ret['is_send']
                self._handler_template = 'user/reg_step_1.html'
                self.render(self._handler_template)
                return
            self.redirect("/reg/?step=2")
            return
        elif next_step == '3':
            self.redirect("/reg/?step=3")
        elif next_step == 'end':
            #保存推荐的朋友和活动信息

            self.redirect("/activity")
        else:
            self._handler_template = "user/reg_step_end.html"
        self._context.error = error
        self.render(self._handler_template)

    #获取性格列表
    def getChaList(self):
        bfi = BfiCharacterTest()
        return bfi.getAll()

    #活动推荐
    def getSocialGroups(self):
        group = SocialGroup()
        page_num = self.get_argument("stpage_numep", 1)
        group_list = group.getSocialGroupList(page_num)
        self._context.group_list = group_list

    def get(self):
        self._context.error = ''
        step = self.get_argument("step", 0)
        self._context.next = self.get_next_url()
        #获取用户uid
        user_info = None
        uid = self.get_secure_cookie('uid', None)
        if (step == '1' or step == '2' or step == '3'
                or step == 'end') and (not uid):
            self.redirect('/reg/?step=0')
            return
        else:
            #获取用户信息
            user_info = self.user.getItem(uid)
        if urlparse.urlparse(self._context.next).path == '/reg':
            self._context.next = '/index'
        if step == '0':
            self.assignDirection()
            if uid:
                self._context.user_info = user_info
                self._context.area = ','.join(
                    self.d.getDistrictParents(user_info['area_id'], res=[]))
            else:
                self._context.user_info = None
            self._handler_template = 'user/reg.html'
        elif step == '1':
            #判断用户是否保存到cookie中
            if not uid:
                self.redirect('/reg/?step=0')
            #获取用户信息
            user_info = self.user.getItem(uid)
            self._context.user_info = user_info
            self._context.user_email = user_info['user_email']
            #判断是否给用户发送了邮件
            self._context.is_send = True
            uv = UserVerify()
            uv_info = uv.getVerifyInfo(uid)
            if uv_info:
                #不需要发送邮件
                self._context.is_send = False
                #验证url没有过期
                now = int(time.mktime(datetime.datetime.now().timetuple()))
                if user_info[
                        'is_verify'] != 1 and utiles.formateDateToTimestamp(
                            uv_info['verify_expire_time']) > now:
                    self._context.error = ErrorMessage.error_message['016']
                elif user_info[
                        'is_verify'] != 1 and utiles.formateDateToTimestamp(
                            uv_info['verify_expire_time']) <= now:
                    self._context.is_send = True
            self._handler_template = 'user/reg_step_1.html'

        elif step == '2':
            #判断是否给用户发送了邮件
            ret = self.checkTokenUrl(uid)
            self._context.is_send = True if ret['code'] == 'success' else False
            if ret['code'] == 'error':
                self._context.error = ret['msg']
                self._handler_template = 'user/reg_step_1.html'
            else:
                list = self.getChaList()
                self._context.list = list
                self._context.ids = ','.join(
                    [str(item['id']) for item in list])
                self._handler_template = 'user/reg_step_2.html'

        elif step == '3':
            ut = UserBfiTest()
            ut_info = ut.queryOne(filterString=[('uid', uid)],
                                  fields=ut._table_columns)
            if ut_info:
                #获取性格测试平均值
                sysconfig = SysConfig()
                bfi_vals = sysconfig.getConfig('bfi_total')
                bfi_user_total = int(
                    sysconfig.getConfig('bfi_user_total')['val'])

                #建立雷达图
                config = Config()
                config.explicit_size = True
                config.width = 500
                config.height = 450
                config.label_font_size = 14
                config.x_label_rotation = 1
                radar_chart = pygal.Radar(config)
                radar_chart.title = u'人格初测结果'
                radar_chart.x_labels = [
                    u'开放性O', u'神经质N', u'宜人性A', u'外向型E', u'尽职性C'
                ]
                radar_chart.add(user_info['user_name'], [
                    int(ut_info['O_val']),
                    int(ut_info['N_val']),
                    int(ut_info['A_val']),
                    int(ut_info['E_val']),
                    int(ut_info['C_val'])
                ])
                radar_chart.add(u'平均值', [
                    bfi_vals['O'] / bfi_user_total, bfi_vals['N'] /
                    bfi_user_total, bfi_vals['A'] / bfi_user_total,
                    bfi_vals['E'] / bfi_user_total,
                    bfi_vals['C'] / bfi_user_total
                ])
                self._context.radar = radar_chart.render()
                #评价
                self._context.N_msg = BfiCharacterTest.transform(
                    'N', int(ut_info['N_val']))[0]
                self._context.O_msg = BfiCharacterTest.transform(
                    'O', int(ut_info['O_val']))[0]
                self._context.A_msg = BfiCharacterTest.transform(
                    'A', int(ut_info['A_val']))[0]
                self._context.E_msg = BfiCharacterTest.transform(
                    'E', int(ut_info['E_val']))[0]
                self._context.C_msg = BfiCharacterTest.transform(
                    'C', int(ut_info['C_val']))[0]
                #从人格特点推荐好友

                #活动推荐

            else:
                self._context.radar = None

            self._handler_template = 'user/reg_step_3.html'

        #跳转到活动列表页
        elif step == 'end':
            self.redirect('/activity')

        self.render(self._handler_template)
        return
コード例 #12
0
 def f**k(self):
     user = User()
     res = user.queryBySql('select sleep(20);')
     raise gen.Return(res)
コード例 #13
0
    def get(self):
        _handler_template = 'feedback/index.html'
        sort_type = self.get_argument('sort', 'rank_sort')
        self._context.sort_type = sort_type

        page = self.get_argument('page', 1)
        limit = options.page_limit['feedback_limit']

        #分页url
        page_url = 'feedback/'
        args_url = ''

        #是否有tag参数
        tag = self.get_argument('tag', '')
        keyword = self.get_argument('keyword', '')
        self._context.keyword = keyword

        conds = {}
        if tag:
            page_url += '&tag='+tag if page_url.find('?')>=0 else '?tag='+tag
            args_url += '&tag='+tag
            conds['tag'] = tag

        if keyword:
            if page_url.find('?')>=0:
                page_url += '&keyword='+keyword
            else:
                page_url += '?keyword='+keyword
            args_url += '&keyword='+keyword
            conds['keyword'] = keyword

        #传递请求url
        self._context.form_url = page_url
        self._context.args_url = args_url

        feedback = Feedback()
        feedback_total = feedback.getListTotal(conds)
        #分页
        page_obj = Page(total_entries=int(feedback_total.total), entries_per_page=int(limit), current_page=page)
        page_obj.current_page(page)

        feedback_list = feedback.getList(conds=conds, sorting=sort_type, page=page_obj.current_page(), limit=limit)
        page_str = page_obj.getPageStr('/feedback')
        self._context.page_str = page_str
        #
        (list, res, tag_ids, uids) = ([], [], [], [])
        for item in feedback_list:
            item['votes'] = item['oppose_votes']+item['approval_votes']
            temp_tag_ids = item['tag_ids'].split(',')
            for t in temp_tag_ids:
                if t:
                    tag_ids.append(t)
            uids.append(item['uid'])
            item['title'] = filterTags(utiles.cutStr(item['title']), True)
            item['tag_ids'] = temp_tag_ids
            list.append(item)

        feedback_tag = FeedbackTags()
        tag_list = feedback_tag.getTagListByIds(tag_ids)
        del tag_ids

        #获取用户
        user = User()
        user_list = user.getUsersByUids(uids)

        for item in list:
            item['user_info'] = user_list[item['uid']] if user_list[item['uid']] else {'user_name':''}
            item.pop('uid')
            item['tags'] = []
            for i in item['tag_ids']:
                if i and tag_list.has_key(int(i)):
                    item['tags'].append(tag_list[int(i)])
            item['create_time'] = utiles.timeBefore(item['create_time'])
            if item['views']>9999:
                item['views'] = '9999+'
            res.append(item)
        del list
        self._context.feedback_list = res
        self.render(_handler_template)
コード例 #14
0
class InfoHandler(BaseHandler):

    feedback = Feedback()
    feedback_tag = FeedbackTags()
    feedback_comment = FeedbackComment()
    user = User()

    #获取评论列表以及评论的回复列表
    def getComentsAndReplies(self, fid, page, limit):

        #获取评论总数
        comment_total = self.feedback_comment.getFeedbackCommentCountByFid(fid)

        #获取评论
        comments = self.feedback_comment.getFeedbackCommentsByFid(fid, page, limit)

        user_ids = []
        comment_ids = []
        for (k, v) in comments.items():
            user_ids.append(v['uid'])
            comment_ids.append(v['id'])
        #获取评论的回复列表
        reply_list = self.feedback_comment.getSonFeedbackCommentByAncestorId(comment_ids, 1, 100)

        for (k, v) in reply_list.items():
            for i in v:
                user_ids.append(i['uid'])
                user_ids.append(i['to_uid'])

        #评论者集合
        user_infos = self.user.getUsersByUids(user_ids)

        for (key, item) in comments.items():
            item['commenter'] = user_infos[item['uid']] if user_infos[item['uid']] else {'user_name':''}
            item['create_time'] = utiles.timeBefore(item['create_time'])
            temp_reply_list = reply_list.get(item['id'], [])
            temp_new_reply_list = []
            for i in temp_reply_list:
                i['commenter'] = user_infos[item['uid']] if user_infos[item['uid']] else {'user_name':''}
                i['create_time'] = utiles.timeBefore(i['create_time'])
                i['to_user_name'] = user_infos[item['to_uid']]['user_name'] if item['to_uid']!=0 and user_infos[item['to_uid']] else ''
                i['to_user_id'] = item['to_uid']
                temp_new_reply_list.append(i)
            item['reply_list'] = temp_new_reply_list
            del temp_new_reply_list, temp_reply_list
            comments[key] = item

        return comment_total, comments

    @unblock
    def get(self, id):
        if not id:
            self.render_404()

        #更新查看总数
        self.feedback.updateFeedbackCount(id, 'views')

        uid = self.get_current_user(info=False)

        page = self.get_argument('page', 1)
        limit = options.page_limit['feedback_limit']
        _handler_template = 'feedback/feedback_info.html'
        feedback_info = self.feedback.getFeedbackById(id)

        if not feedback_info:
            return self.render_404()

        feedback_info['tags'] = self.feedback_tag.getTagListByIds(feedback_info['tag_ids'].split(','))
        feedback_info['user_info'] = self.user.getItem(feedback_info['uid'])
        feedback_info['publish_time'] = utiles.timeBefore(feedback_info['create_time'])
        self._context.feedback_info = feedback_info

        comment_total, comments = self.getComentsAndReplies(feedback_info['id'], page, limit)

        self._context.comment_total = str(comment_total['total'])
        self._context.comments = comments

        #判断是否显示‘查看更多’
        show_more = None
        if comment_total['total']>limit:
            show_more = True
        self._context.show_more = show_more
        self._context.show_more_url = '/feedback/info/%d' % int(id)
        self._context.page = page
        self._context.relay_click_time = options.relay_click_time
        self._context.r = time.time()

        if checkNeedCaptcha(FEEDBACK_COMMENT_KEY, uid):
            self._context.is_need_captcha = 1
        else:
            self._context.is_need_captcha = None

        self.render(_handler_template)
        self.finish()

    @unblock
    def post(self, fid):
        #ajax请求获取评论的分页信息
        page = self.get_argument('page', 1)
        limit = options.page_limit['feedback_limit']
        if not fid:
            self.return_json({'res': None, 'code': 'error'})

        comment_total, comments = self.getComentsAndReplies(fid, page, limit)

        #判断是否显示‘查看更多’
        show_more = 0
        if int(math.ceil(comment_total['total']/limit))>=int(page):
            show_more = 1

        self.return_json({'res': {'comments': comments, 'fid': fid, 'show_more': show_more, 'page': page}, 'code': 'success'}, date_encoder=True, finish=True)
        return