def search_dicts(query, category): ''' category in ('share', 'event', 'club') 返回 yield 体 ''' if category == 'share': for i in ShareSnap.share_search(query): yield { 'data': i, 'avatar': ShareSnap.thumbnail_find(i.attach_uuid, 'medium') or \ AvatarSnap.avatar_find \ (i.relation, i.account_id, 'medium'), } elif category == 'event': for i in EventSnap.event_search(query): yield { 'data': i, 'avatar': AvatarSnap.avatar_all(i.relation, i.account_id), } else: for i in ClubSnap.club_search(query): yield { 'data': i, 'avatar': AvatarSnap.avatar_all('club', i.id), }
def total_rank(club, detail=False): 'event + share + watch, 当三无时返回0' cid = club.id cache_key = 'SquareSnap__total_rank__%d' % cid cached = cache.get(cache_key) if cached: if detail: return cached else: return cached['rank'] rank = 0 event_num = EventSnap.event_find_by_cid('club', cid).count() share_num = ShareSnap.share_find_by_aid('club', cid).count() follower_num = ClubSnap.follower_total(cid) avatar_num = int(bool(AvatarSnap.avatar_find('club', cid, '', True))) rank += 20 * event_num rank += 15 * share_num rank += 10 * follower_num rank += 30 * avatar_num answer = { 'rank': rank, 'event_num': event_num, 'share_num': share_num, 'follower_num': follower_num, 'avatar_num': avatar_num, } cache.set(cache_key, answer, random.randint(800000, 900000)) if detail: return answer else: return rank
def intro(src, aid): dict_intro = { 'avatar': AvatarSnap.avatar_find(src, aid), 'badge_list': BadgeSnap.badge_find_by_cid(src, aid), # badge_list => USer? } return dict_intro
def share_show(suid): from quan_event.views import EventSnap share = ShareSnap.share_find_by_uuid(suid) if not share: raise Http404() src = share.relation aid = share.account_id dict_render = { 'data': share, 'share_content': share.content.split('\n'), 'visitors': AccountSnap.visit_count_by_account(share), } dict_render['sname'] = AccountSnap.sname_find_by_aid( share.relation, share.account_id) dict_render['fname'] = AccountSnap.fname_find_by_aid( share.relation, share.account_id) date, time = ChineseSnap.datetime_comp(share.time_create) dict_render['time'] = date + ' ' + time dict_render['avatar'] = AvatarSnap.avatar_find(src, aid) dict_render['file_list'] = ShareSnap.file_list_find_by_suid(suid) dict_render['image_list'] = ShareSnap.image_list_find_by_suid(suid) dict_render['stream_list'] = ShareSnap.stream_list_find_by_suid(suid) # dict_render['chat_list'] = ShareSnap.chat_find(share.id) dict_render['title'] = t_(' - %s - %s的分享') % (share.subject, dict_render['fname']) archive_qry = ShareAttach.objects.filter \ (attach_uuid=suid, category='archive') if archive_qry: dict_render['archive_size'] = ChineseSnap.byte_exchange \ (archive_qry[0].size) return dict_render
def member_manage(src, aid, render_list=('follower', 'member', 'wait')): '按照render_list中的要求选择性渲染' if src == 'user': return {} dict_render = {'member_wait': [], 'member': []} if 'wait' in render_list: # 待审核社员 mem_wait = ClubSnap.member_wait_find(aid) dict_render['member_wait_num'] = len(mem_wait) for i in mem_wait: time_create_tumple = ChineseSnap.datetime_simp(i.time_create) user = { 'name': UserSnap.fname_find_by_uid(i.account_id_A), 'grade': UserSnap.grade_find_by_uid(i.account_id_A, True), 'date': time_create_tumple[0], 'id': i.account_id_A, } dict_render['member_wait'].append(user) if 'member' in render_list: # 通过社员 for uid in ClubSnap.member_all(aid): join, total = EventSnap.event_attendence_by_uid(uid, aid) user = { 'uid': uid, 'name': UserSnap.fname_find_by_uid(uid), 'grade': UserSnap.grade_find_by_uid(uid, True), 'ratio': '%.1f' % \ (100.0 * (total / timedelta(1) and join / total)), 'score': '%.1f' % (0.2 * join / timedelta(0, 3600)), 'identity': ClubSnap.club_position_by_uid(aid, uid), 'avatar': AvatarSnap.avatar_find('user', uid, 'medium'), } dict_render['member'].append(user) if 'follower' in render_list: # 跟随者 qry = ClubSnap.follower_find(aid) follower_list = [] for i in qry: follower_list.append({ 'data': UserSnap.user_find_by_uid(i.account_id_A), 'avatar': AvatarSnap.avatar_find('user', i.account_id_A, size="medium"), }) dict_render['follower_list'] = follower_list return dict_render
def club_all(request, qry, category='all'): uid = UserSnap.uid_find_by_request(request) club_list = [] for i in qry: club_dict = {'data': i} club_dict['avatar'] = AvatarSnap.avatar_all('club', i.id) club_dict['follow'] = ClubSnap.follower_total(i.id) club_dict['followed'] = ClubSnap.club_followed_by_uid(uid, i.id) club_dict['followee'] = list(itertools.islice \ (ClubSnap.follower_list(i.id), 3)) club_dict['category'] = ClubSnap.category_exchange(i.category) club_list.append(club_dict) return club_list
def chat_find(sid): '得到谈话列表(废弃可能)' qry = PrivateMessage.objects.filter \ (conn_id=sid, conn_relation='share-im', recv_id=sid, recv_relation='share').order_by('-time_create') chat_list = [] for i in qry: uid = UserSnap.uid_find_by_sname(i.subject) chat_list.append({ 'data': i, 'avatar': AvatarSnap.avatar_find('user', uid) }) return chat_list
def home_dict(request): '得到/页面的字典,喜欢=关注' dict_render = {} #得到3个最新活动 dict_render['event_list'] = [] event_qry = SquareSnap.event_newest() for i in event_qry: event_date, event_time = ChineseSnap.datetime_simp(i.time_set) dict_render['event_list'].append({ 'data': i, 'nice': EventSnap.nice_total(i.id), 'date': event_date, 'time': event_time, 'niced': EventSnap.niced_find_by_request(request, i.id), 'sname': ClubSnap.sname_find_by_cid(i.account_id), 'fname': ClubSnap.fname_find_by_cid(i.account_id), }) dict_render['club_list'] = [] club_all = ClubSnap.club_all_find() club_list = [] for i in club_all: club_list.append((i, SquareSnap.total_rank(i, True))) club_filtered = list(filter(lambda x: all(x[1].values()), club_list)) # 抵制三无社团 club_filtered.sort(key=lambda x: x[1]['rank'], reverse=True) num = min(3, max(0, len(club_filtered) - 3)) club_qry = club_filtered[:3] + random.sample(club_filtered[3:], num) for club, rank in club_qry: dict_render['club_list'].append({ 'data': club, 'avatar': AvatarSnap.avatar_find('club', club.id, 'medium'), 'follower': ClubSnap.follower_total(club.id), 'followee': ', '.join(itertools.islice \ (ClubSnap.follower_list(club.id), 3)), 'category': ClubSnap.category_exchange(club.category), }) # 得到社联通知列表 dict_render['note'] = ShareSnap.union_record_find() if AuthSnap.notice_check(UserSnap.uid_find_by_request(request), dict_render['note']): dict_render['note_read'] = True return dict_render
def funds_list(request, sname): '资金申请: 显示社团的所有' dict_render = UserAgentSnap.record(request) aid = ClubSnap.cid_find_by_sname(sname) UserAuthority.assert_permission(request, 'club', aid) head = ClubSnap.head_find_by_cid(aid) dict_render['head'] = head head_account = UserSnap.account_find_by_uid(head.id) dict_render['head_phone'] = head_account.phone dict_render['avatar'] = AvatarSnap.avatar_find('club', aid, 'raw') dict_render['head_grade'] = UserSnap.grade_translate \ (head_account.grade) dict_render['club'] = ClubSnap.club_find_by_cid(aid) qry = AuthInfo.objects.filter( account_id=aid, relation='funds').exclude(data='deleted').order_by('-time_update') dict_render['funds_list'] = AuthDicts.funds_list(qry, need_club=False) fname = dict_render['club'].full_name dict_render['title'] = t_(' - 资金申请列表 - %s') % fname return Snap.render('funds_list.html', dict_render)
def follower_list(request, sname): '/club/[sname]/follower/' dict_render = UserAgentSnap.record(request) real_name = ClubSnap.alias_find_by_sname(sname) if real_name != sname and real_name: return Snap.redirect('/club/%s/follower/' % real_name) aid = AccountSnap.aid_find_by_sname('club', sname) qry = ClubSnap.follower_find(aid) follower_list = [] for i in qry: follower_list.append({ 'data': UserSnap.user_find_by_uid(i.account_id_A), 'avatar': AvatarSnap.avatar_all('user', i.account_id_A), 'nickname': UserSnap.nickname_find_by_uid(i.account_id_A)[:5], }) dict_render['follower_list'] = follower_list fname = ClubSnap.fname_find_by_cid(aid) dict_render['title'] = t_(' - %s - 订阅用户') % fname return Snap.render('club_follower.html', dict_render)
def square_event(data, belong, request): '复制每块的字典' item = {'data': data} # 渲染的模块名 item['belong'] = belong # 开始时间 time_set = data.time_set item['day_set'], item['time_set'] = ChineseSnap.datetime_comp(time_set) # 头相、赞、关注、发起者 cid = data.account_id item['follower'] = EventSnap.follower_total(data.id) item['nice'] = EventSnap.nice_total(data.id) item['avatar'] = AvatarSnap.avatar_find(data.relation, cid, 'medium') item['sponsor'] = ClubSnap.sname_find_by_cid(cid) item['sponsor_fname'] = ClubSnap.fname_find_by_cid(cid) # 持续时间 item['time_last'] = ChineseSnap.timedelta_comp(data.time_end - time_set) # 是否已经关注/赞 item['niced'] = EventSnap.niced_find_by_request(request, data.id) item['followed'] = EventSnap.followed_find_by_request(request, data.id) return item
def wall(): '/wall/' dict_render = {} club_dict = {} for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ#": club_dict[letter] = [] qry = ClubSnap.club_all_find() for club in qry: club_dict[SquareSnap.capital_find(club)].append({ 'data': club, 'avatar': AvatarSnap.avatar_find('club', club.id, 'small'), }) wall_list = list(club_dict.items()) wall_list.sort(key=lambda x: {'#': 'a'}.get(x[0], x[0])) # 这个 lambda 的含义: 如果是'#'则返回a(会被放到最后),否则返回本身(如'H') dict_render['club_section'] = wall_list dict_render['club_num'] = qry.count() current_date = ChineseSnap.datetime_simp(datetime.now()) dict_render['current_date'] = current_date[0] + current_date[1] return dict_render
def single_event(request, evid) : event = EventSnap.event_find_by_evid(evid) if not event : return None evid = int(evid) event_dict = {'data':event,} date_string, time_end = ChineseSnap.datetime_comp(event.time_end) date_string, time_string = ChineseSnap.datetime_comp(event.time_set) event_dict['content'] = event.content.split('\n') event_dict['day_set'] = date_string event_dict['time_set'] = time_string event_dict['time_end'] = time_end event_dict['avatar'] = AvatarSnap.avatar_find(event.relation, event.account_id) event_dict['follower'] = EventSnap.follower_total(evid) event_dict['nice'] = EventSnap.nice_total(evid) event_dict['niced'] = EventSnap.niced_find_by_request(request, evid) event_dict['event_followed'] = EventSnap.followed_find_by_request(request, evid) if event.relation=='user': event_dict['sponsor_fname'] = '用户' + str(event.account_id) else: event_dict['sponsor_fname'] = ClubSnap.fname_find_by_cid \ (event.account_id) event_dict['sponsor_sname'] = AccountSnap.sname_find_by_aid(event.relation, event.account_id) president = ClubSnap.cid_verify(request, event.account_id, True) event_dict.update(EventSnap.signed_get_by_event(event)) event_dict['follower_list'] = EventSnap.follower_find_by_evid(event.id) event_dict['quest'] = EventSnap.quest_find_by_evid(event.id) time_status = EventSnap.time_status(event) # 计算需要显示的模块 event_dict['president'] = president show = () if president : if time_status == 0 and not event_dict['quest'] : show = ('signup_set', ) elif time_status != -1 : show = ('join', 'signup_manual') if time_status == 0 : event_dict['signup_qrcode'] = \ EventSnap.signup_qrcode_find_by_evid(evid) else : uid = UserSnap.uid_find_by_request(request) if time_status == 0 and event_dict['quest'] : if uid and not EventSnap.signed_find_by_uid(evid, uid) : show = ('signup', ) for i in show : event_dict['show_%s' % i] = True # 为 share 和 event 关联渲染 from quan_share.views import ShareSnap event_dict['share_list'] = [[]] event_dict['related_list'] = [] related_list = [] for i in ShareEventRelation.objects.filter(event_id=evid, status=0) : related_list.append(i.share_id) club_avatar = AvatarSnap.avatar_find \ (event.relation, event.account_id, 'large') for i in ShareSnap.share_find_by_aid(event.relation, event.account_id) : thumbnail = '' if i.id in related_list : event_dict['relate_exist'] = True thumbnail = ShareSnap.thumbnail_find(i.attach_uuid, 'large') if not thumbnail : thumbnail = club_avatar append_object = { 'data': i, 'related': i.id in related_list, 'date': ChineseSnap.datetime_simp(i.time_create), 'thumbnail': thumbnail, 'content': i.content.split('\n'), } if len(event_dict['share_list'][-1]) < 10 : event_dict['share_list'][-1].append(append_object) else : event_dict['share_list'].append([append_object]) return event_dict
def user_show(request, sname): dict_render = UserAgentSnap.record(request) uid = UserSnap.uid_find_by_sname(sname) user = UserSnap.user_find_by_uid(uid) visitor_id = UserSnap.uid_find_by_request(request) if not user: raise Http404('找不到用户') dict_render['title'] = t_(' - %s的主页') % user.first_name dict_render['user'] = user dict_render['club_join'] = [] dict_render['club_follow'] = [] club = list(ClubSnap.club_find_by_uid(uid)) club += list(ClubSnap.club_find_by_uid(uid, False)) for i in set(club): event = EventSnap.event_find_by_cid('club', i.id) event_list = [] for j in list(event)[-3:]: evtime = ChineseSnap.datetime_simp(j.time_create) event_list.append({ 'data': j, 'datetime': evtime[0] + evtime[1], 'join': EventSnap.signup_total(j.id), }) member = ClubSnap.member_all(i.id) member_nickname = [] for j in list(member)[:3]: member_nickname.append(UserSnap.nickname_find_by_uid(j)) follower_qry = ClubSnap.follower_find(i.id) follower_nickname = [] for j in follower_qry[:3]: follower_nickname.append \ (UserSnap.nickname_find_by_uid(j.account_id_A)) position = ClubSnap.club_position_by_uid(i.id, uid) club_dict = { 'data': i, 'position': position[1], 'event_list': sorted(event_list, key=lambda x: x['data'].time_set, reverse=True), 'event_num': event.count(), 'member_nickname': t_(',').join(member_nickname), 'member_num': len(member), 'member_gt_3': len(member) > 3, 'follower_nickname': t_(',').join(follower_nickname), 'follower_num': follower_qry.count(), 'follower_gt_3': follower_qry.count() > 3, 'avatar': AvatarSnap.avatar_all('club', i.id), 'visitor_join': ClubSnap.club_position_by_uid \ (i.id, UserSnap.uid_find_by_request(request))[0] != 'none', } if position[0] != 'none': dict_render['club_join'].append(club_dict) if ClubSnap.club_followed_by_uid(uid, i.id): dict_render['club_follow'].append(club_dict) dict_render['title'] = t_(' - %s的主页') % user.first_name account = UserSnap.account_find_by_uid(uid) dict_render['visit_count'] = AccountSnap.visit_count_by_account( account) dict_render['join_time'] = ChineseSnap.timedelta_simp \ (datetime.now() - user.date_joined) if UserSnap.sname_find_by_request(request) == sname: # user_admin dict_render['inc_admin'] = True dict_render['user_avatar'] = AvatarSnap.avatar_all('user', uid) if dict_render['user_avatar']['raw'].startswith('/static/'): if random.randint(1, 3000) % 3 == 0: # 强制上传头像 return Snap.redirect('/avatar/user/%s/' % sname) dict_render.update(BadgeDicts.intro('user', uid)) dict_render.update(CenterDicts.club_find(uid)) dict_render['nickname'] = UserSnap.nickname_find_by_uid(uid) dict_render['badge_list'] = BadgeDicts.badge_find('user', uid) dict_render['contact_club'] = dict_render['club_join'] dict_render['contact_user'] = [] for i in UserSnap.contact_list(uid): data = UserSnap.user_find_by_uid(i) dict_render['contact_user'].append({ 'data': data, 'avatar': AvatarSnap.avatar_all('user', i), 'nickname': UserSnap.nickname_find_by_uid(i), }) dict_render['share_list'] = [] share_qry = ShareSnap.share_find_by_aid('user', uid) for i in share_qry: dict_render['share_list'].append({ 'data': i, 'date': ChineseSnap.datetime_simp(i.time_create), }) dict_render['tab_active'] = request.GET.get('tag', 'messages') dict_render['tab_list'] = [ ( 'messages', '消息', ), ( 'club', '我的社团', ), ( 'follow', '订阅列表', ), ( 'footprint', '我的足迹', ), ( 'friends', '好友动态', ), ( 'share', '我的分享', ), ( 'settings', '设置', ), ] dict_render['system_avatar'] = AvatarSnap.avatar_all('system', 0) return Snap.render('user_admin.html', dict_render) else: # user_view user = UserSnap.user_find_by_uid(uid) club = list(ClubSnap.club_find_by_uid(uid, True)) + \ list(ClubSnap.club_find_by_uid(uid, False)) dict_render['followed'] = UserSnap.is_follower(uid, visitor_id) dict_render['friend'] = UserSnap.is_friend(uid, visitor_id) friend_status = UserSnap.friend_status_find(uid, visitor_id) dict_render['friend_status'] = friend_status if friend_status == 'friend': dict_render['friend_status_text'] = t_('取消好友') dict_render['friend_active_tag'] = '' dict_render['friends'] = True elif friend_status == 'friend-waiting': #visitor等待 dict_render['friend_status_text'] = t_('正在等待对方审核') dict_render['friend_active_tag'] = 'active' elif friend_status == 'friend-waiting-reverse': #visitor需要确认 dict_render['friend_status_text'] = t_('同意申请') dict_render['friend_active_tag'] = '' dict_render['friend_need_verify'] = True else: # none dict_render['friend_status_text'] = t_('加为好友') dict_render['friend_active_tag'] = '' event_list = [] for event in list(EventSnap.event_find_by_uid(uid))[:10]: event_time = list(ChineseSnap.datetime_simp(event.time_set)) event_time[0] = event_time[0][:-1] event_dict = { 'club': ClubSnap.club_find_by_cid(event.account_id), 'club_avatar': AvatarSnap.avatar_all \ ('club', event.account_id), 'data': event, 'join_num': EventSnap.signup_total(event.id), 'datetime': event_time, } if event.time_set < datetime.now(): event_list.append(event_dict) elif not 'event_next' in dict_render: dict_render['event_next'] = event_dict dict_render['event_list'] = event_list dict_render['nickname'] = UserSnap.nickname_find_by_uid(uid) dict_render['avatar'] = AvatarSnap.avatar_all('user', uid) return Snap.render('user_view.html', dict_render)
def chat_wrap(qry, recv_id): ''' 为 PrivateMessage 写的 qry->list 函数 其中 send_src 和 send_id 表明期望的 host_id 返回 yield 体 ''' from quan_event.views import EventSnap from quan_avatar.views import AvatarSnap from quan_account.views import ClubSnap, AccountSnap, UserSnap from quan_ua.views import ChineseSnap message_list = [] for i in qry: # user A = 自身 # user B = 好友 # club C = 一个社团 # 可能出现的情况 host avatar # user # A -> B B A # B -> A B B # club # C -> A C C # A -> C C A # B -> C C B host_src, host_id = PrivateMessageAction.get_host(i, recv_id) src = i.conn_relation if i.send_id == recv_id and i.send_relation == 'user': if src == 'share': src = 'share-self' else: src = 'self' elif src == 'none': src = 'other' if i.send_relation == 'user' and src == 'share': src = 'share-other' message_dict = { 'content': i.content, 'time_update': ChineseSnap.datetime_simp(i.time_create), 'url': PrivateMessageAction.link_find(i), 'avatar': AvatarSnap.avatar_all(i.send_relation, i.send_id), 'type': src, 'host_id': host_id, 'host_src': host_src, 'time_stamp': i.time_create.timestamp(), } aid = i.conn_id if src in ('share', 'share-self', 'share-other'): from quan_share.views import ShareSnap qry = ShareSnap.share_find_by_sid(aid) if qry: from quan_share.views import ShareSnap message_dict.update({ 'data': { 'subject': qry.subject, 'uuid': qry.attach_uuid }, 'attach': ShareSnap.file_list_find_by_suid \ (qry.attach_uuid, True), }) elif src in ('event', 'event-signup'): from quan_event.views import EventSnap qry = EventSnap.event_find_by_evid(aid) if not qry: continue club = ClubSnap.club_find_by_cid(qry.account_id) if not club: continue message_dict.update({ 'data': { 'subject': qry.subject, 'location': qry.location, 'content': qry.content, 'id': qry.id, }, 'avatar': AvatarSnap.avatar_all(qry.relation, qry.account_id), 'club': { 'full_name': club.full_name }, 'date': ChineseSnap.datetime_simp(qry.time_set), }) elif src == 'badge': from quan_badge.views import BadgeSnap qry = BadgeSnap.badge_find_by_bid(aid) if not qry: continue club = ClubSnap.club_find_by_cid(qry.account_id) if not club: continue message_dict.update({ 'name': qry.name, 'club': { 'simp_name': club.simp_name }, }) elif src in ('friend', 'hi'): aid = i.send_id message_dict.update({ 'avatar': AvatarSnap.avatar_all('user', aid), 'nickname': UserSnap.nickname_find_by_uid(aid), 'id': aid, 'sname': UserSnap.sname_find_by_uid(aid), 'disable': '', }) if AccountSnap.relation_check \ (recv_id, aid, ('uu-friend', 'uu-friend-wait')) : message_dict['disable'] = 'disabled="disabled"' elif src == 'leave': message_dict.update({ 'cname': ClubSnap.fname_find_by_cid(i.conn_id), 'fname': UserSnap.fname_find_by_uid(i.send_id), }) else: # other, self message_dict.update({ 'avatar': AvatarSnap.avatar_all(i.send_relation, i.send_id), 'nickname': AccountSnap.nickname_find_by_aid \ (i.send_relation, i.send_id), }) if i.send_id == recv_id and i.send_relation == 'user': message_dict['type'] = 'self' yield message_dict
def account_info_find(src, aid): ''' 得到用户/社团的信息字典(为了返回json消息) ''' from quan_avatar.views import AvatarSnap from quan_account.views import UserSnap, ClubSnap, AccountSnap from quan_forum.views import ForumSnap default = { 'link': '', 'text': '', 'image': '', } if src == 'club': return { 'link': '/club/%s/' % ClubSnap.sname_find_by_cid(aid), 'text': ClubSnap.fname_find_by_cid(aid), 'image': AvatarSnap.avatar_find('club', aid, 'small'), } elif src == 'user': return { 'link': '/user/%s/' % UserSnap.sname_find_by_uid(aid), 'text': UserSnap.nickname_find_by_uid(aid), 'image': AvatarSnap.avatar_find('user', aid, 'small'), } elif src == 'event': from quan_event.views import EventSnap event = EventSnap.event_find_by_evid(aid) if not event: return default cid = event.account_id return { 'link': '/event/%d/' % aid, 'text': event.subject, 'image': AvatarSnap.avatar_find('club', cid, 'small'), } elif src == 'share': from quan_share.views import ShareSnap share = ShareSnap.share_find_by_sid(aid) if not share: return default suid = share.attach_uuid return { 'link': '/share/%s/' % suid, 'text': share.subject, 'image': ShareSnap.thumbnail_find(suid, 'small') or \ AvatarSnap.avatar_find \ (share.relation, share.account_id, 'small'), } elif src == 'badge': from quan_badge.views import BadgeSnap badge = BadgeSnap.badge_find_by_bid(aid) if not badge: return default sname = ClubSnap.sname_find_by_cid(badge.account_id) return { 'link': '/club/%s/' % sname, 'text': badge.name, 'image': None, } elif src == 'news': from quan_news.views import NewsSnap news = NewsSnap.news_find(aid) if not news: return default return { 'link': '/news/%d/' % aid, 'text': news.subject, 'image': None, } elif src == 'signature': user = UserSnap.user_find_by_uid(aid) if not user: return default return { 'link': '/user/%s/' % user.last_name, 'text': UserSnap.signature_find_by_uid(aid), 'image': None, } elif src == 'nickname': user = UserSnap.user_find_by_uid(aid) if not user: return default return { 'link': '/user/%s/' % user.last_name, 'text': UserSnap.nickname_find_by_uid(aid), 'image': None, } elif src == 'forum_thread': thread = ForumSnap.thread_find_by_thid(aid) sname = ForumSnap.sname_find_by_gid(thread.group_id) return { 'link': '/forum/%s/%d/' % (sname, aid), 'text': thread.subject, 'image': None, } elif src == 'forum_response': thid = ForumSnap.thid_find_by_rid(aid) thread = ForumSnap.thread_find_by_thid(thid) sname = ForumSnap.sname_find_by_gid(thread.group_id) return { 'link': '/forum/%s/%d/?response=%d#response-%d' % \ (sname, thid, aid, aid), 'text': thread.subject, 'image': None, } else: return default
def funds_apply(request, sname, apply=False): '资金申请: 添加条目' dict_render = UserAgentSnap.record(request) if apply: aid = ClubSnap.cid_find_by_sname(sname) UserAuthority.assert_permission(request, 'club', aid) else: funds_id = int(sname) qry = AuthInfo.objects.filter(relation='funds', stars=funds_id) if not qry or qry[0].data == 'deleted': raise Http404() aid = qry[0].account_id UserAuthority.assert_permission(request, 'club', aid) dict_render['funds_form'] = AuthDicts.funds_form() if request.method == 'POST': form_title = request.POST.get('title') if not form_title: raise Snap.error('忘记填写标题?') form_type = request.POST.get('type') if form_type not in ( 'funds', 'borrow', ): raise Snap.error('请选择资金类型') combined_data = [ form_title, form_type, ] for i in dict_render['funds_form']: content = request.POST.get('content' + str(i[0])) if not content: raise Snap.error('表单填写不全,请不要留空任何一项') if i[0] == 1: try: combined_data.append(int(content)) except Exception: raise Snap.error('金额必须是整数') else: combined_data.append(content) if not apply: qry[0].data = 'submitted' qry[0].extra = json.dumps(combined_data) qry[0].save() return Snap.success( request, '修改成功', { 'redirect': '/auth/funds/%s/list/' % ClubSnap.sname_find_by_cid(aid) }) # if apply : for i in range(1000): prefix = int(datetime.now().strftime('%y%m%d')) * 1000 current_qry = AuthInfo.objects.filter( relation='funds', stars__gte=prefix).order_by('-stars') if not current_qry: stars = prefix + 1 else: stars = current_qry[0].stars + 1 if current_qry.filter(stars=stars): continue qry = AuthInfo(account_id=aid, relation='funds', stars=stars, data='submitted', extra=json.dumps(combined_data)) qry.save() return Snap.success( request, '提交成功', { 'redirect': '/auth/funds/%s/list/' % ClubSnap.sname_find_by_cid(aid) }) break raise Snap.error('数据错误') if apply: dict_render['choose_funds'] = True else: dict_render['funds_id'] = funds_id extra = json.loads(qry[0].extra) dict_render['extra'] = extra dict_render['choose_' + extra[1]] = True funds_form = [] index = 2 for i in dict_render['funds_form']: funds_form.append(i + (extra[index], )) index += 1 dict_render['funds_form'] = funds_form head = ClubSnap.head_find_by_cid(aid) dict_render['head'] = head head_account = UserSnap.account_find_by_uid(head.id) dict_render['head_phone'] = head_account.phone dict_render['avatar'] = AvatarSnap.avatar_find('club', aid, 'raw') dict_render['head_grade'] = UserSnap.grade_translate \ (head_account.grade) dict_render['club'] = ClubSnap.club_find_by_cid(aid) dict_render['title'] = ' - 资金申请' return Snap.render('funds_apply.html', dict_render)
def empty_view(request, sname): dict_render = UserAgentSnap.record(request) cid = ClubSnap.cid_find_by_sname(sname) is_head = AccountSnap.aid_verify(request, 'club', cid) is_union = AccountSnap.aid_verify( request, 'club', ClubSnap.cid_find_by_sname('club-union'), True, True) category_list = AuthSnap.category_list \ (UserSnap.uid_find_by_request(request)) club = ClubSnap.club_find_by_cid(cid) if not is_head and not is_union and not category_list: raise Http403 \ ('根据社联方面的要求,只有社长和社联成员才能查看此页面。请确认登录状态') if not club: raise Http404('数据错误,请联系HCC社团') is_category_admin = club.category in category_list performance_qry = AuthInfo.objects.filter( relation='performance', account_id=cid, time_update__gte=EventSnap.semester_start()) # get performance if performance_qry: performance = performance_qry[0] else: performance = AuthInfo \ (relation='performance', account_id=cid, data='preparing') performance.save() if not is_head and not is_union and performance.data == 'preparing': raise Http403('表格尚未公开') if request.method == 'GET': # 处理提交的表单 dict_render['performance'] = performance dict_render['changeable'] = performance.data in \ ('waiting', 'preparing') dict_render['event_location'] = request.GET.get( 'event_location', '') dict_render['event_subject'] = request.GET.get('event_subject', '') dict_render['time_set'] = request.GET.get('time_set', '') dict_render['shareSubject'] = request.GET.get('shareSubject', '') impact_val = [] for i in range(5): impact_val.append(request.GET.get('impact%d' % i, '')) if not any(impact_val): try: impact_val = json.loads(performance.extra) except ValueError: pass # begin rendering impact_form = [ '社团活动反思总结', '与其他社团合作活动', '承办学校活动项目', '社团成果', '加分项申请' ] impact_placeholder = [ '社团本学期的大致活动内容,例如日常开会、日常研讨等。' '若有固定时间也请进行补充说明', '合作活动的名称、时间以及合作社团的名称,外加合作社团社长的联系方式与姓名。' '需要上传可视化资料进行证明,例如照片视频等(在分享中上传)', '学校活动的名称、时间、50字简述。' '需要上传可视化资料进行证明,例如照片视频等(在分享中上传)', '本学期该社团具体都达成了什么成就,如果出杂志刊物的就列举出刊物和刊期', '根据评审方法上的加分项内容进行填写', '暂定是这些,谢谢', ] # 以上为 2015-2016 下学期的版本 impact_form = [ '举办过的社团内部活动', '参与或举办的校级活动', '举办的独立社团展示', '本学期社团活动总结与反思', '加分项申请' ] impact_placeholder = [ '写明次数、时间地点、活动形式等', '活动名称和活动形式', '请参照核心评分标准填写', '字数大约为100字', '照片、视频、文档等证明资料为星级评价的重要标准,请在上方的分享栏中提交', ] dict_render['impact'] = [] for i in range(5): dict_render['impact'].append( (i, impact_form[i], impact_val[i], impact_placeholder[i])) semester_start = EventSnap.semester_start() dict_render['is_head'] = is_head dict_render['is_union'] = is_union dict_render['is_category_admin'] = is_category_admin head = ClubSnap.head_find_by_cid(cid) dict_render['head'] = head head_account = UserSnap.account_find_by_uid(head.id) dict_render['head_phone'] = head_account.phone dict_render['avatar'] = AvatarSnap.avatar_find('club', cid, 'raw') dict_render['head_grade'] = UserSnap.grade_translate \ (head_account.grade) dict_render['club'] = club # 评分表 global_rubric = AuthSnap.get_rubric() category_rubric = AuthSnap.get_rubric(club.category) score = json.loads(performance.score or '[[], []]') dict_render['global_rubric'] = itertools.zip_longest \ (global_rubric, score[0]) dict_render['category_rubric'] = itertools.zip_longest \ (category_rubric, score[1]) dict_render['global_rubric_len'] = len(global_rubric) dict_render['category_rubric_len'] = len(category_rubric) if len(score[0]) == len(global_rubric): dict_render['global_score'] = ' - ' + str(sum(score[0])) if len(score[1]) == len(category_rubric): dict_render['category_score'] = ' - ' + str(sum(score[1])) #活动 event_qry = EventSnap.event_semester_find_by_cid('club', cid).order_by \ ('time_set') dict_render['event_list'] = [] for i in event_qry: dict_render['event_list'].append({ 'data': i, 'join_num': EventSnap.signup_total(i.id), 'datetime': ChineseSnap.datetime_simp(i.time_set), }) if not dict_render['event_location'] and event_qry: dict_render['event_location'] = event_qry.order_by \ ('-time_update')[0].location #分享 sem_start = EventSnap.semester_start() share_qry = ShareSnap.share_find_by_aid('club', cid) share_qry = share_qry.filter(time_create__gte=sem_start, \ category__in=('handout', 'knowledge', 'event', 'news', \ 'record-granted', 'record-denied', 'record-droped', \ 'record-broken', 'record-waiting')) dict_render['share_list'] = [] for i in share_qry: dict_render['share_list'].append(ShareDicts.share_show \ (i.attach_uuid)) #成员构成 member_makeup = [0, 0, 0, 0, 0, 0, 0, 0] for i in ClubSnap.grade_list_by_cid(cid): member_makeup[i] += 1 member_sum = sum(member_makeup) dict_render['member_makeup'] = [] for i in range(7): name = UserSnap.grade_translate(i) style = ' progress-bar-' style += ('danger', 'warning', 'info', 'success', 'info', 'warning', 'danger', 'success')[i % 8] if i > 3: style += ' progress-bar-striped' if member_makeup[i]: dict_render['member_makeup'].append({ 'id': i, 'name': name, 'value': member_makeup[i], 'percent': member_makeup[i] * 1000 // member_sum / 10, 'style': style, }) #星级 star_exchange = (0, 40, 50, 60, 70, 80) star = AuthSnap.star_calc(cid, event_qry, member_makeup, share_qry) if not event_qry or not share_qry: star = 0 score = AuthSnap.star_calc \ (cid, event_qry, member_makeup, share_qry, True) if performance.stars < star: dict_render['is_extended'] = 1 elif performance.stars == star: dict_render['is_available'] = 1 else: dict_render['is_failed'] = 1 dict_render['requirement'] = \ (star_exchange[performance.stars] - score - 1) // 10 + 1 dict_render['requirement_p1d2'] = \ (dict_render['requirement'] + 1) // 2 if dict_render['requirement_p1d2'] <= 0: dict_render['requirement_p1d2'] = 1 dict_render['star_tend_list'] = [0] * performance.stars + [1] * \ (5 - performance.stars) dict_render['star_list'] = [0] * star + [1] * (5 - star) dict_render['star_tend'] = performance.stars fname = dict_render['club'].full_name dict_render['title'] = t_(' - 申请星级 - %s') % fname return Snap.render('empty.html', dict_render) # 显示网页结束 score = request.POST.get('score') if score: # 进行评分 if score == 'category': if not is_category_admin: raise Http403('不是联盟长') index = 1 rubric = AuthSnap.get_rubric(club.category) elif score == 'global': if not is_union: raise Http403('不是社联成员') index = 0 rubric = AuthSnap.get_rubric() else: raise Http404('参数错误') if not rubric: raise Snap.error('请先撰写评分表') score = json.loads(performance.score or '[[], []]') data = json.loads(request.POST.get('data', '[]')) if len(data) != len(rubric): raise Snap.error('数据错误: 长度不一致') number_data = [] # 将 data 中的数据类型转换为 int 或 float for i, j in zip(data, rubric): try: number_data.append(j[1][j[1].index(float(i))]) except ValueError: raise Snap.error(t_('“%s”数据有误') % j[0]) score[index] = number_data performance.score = json.dumps(score) performance.save() return Snap.success(request, '打分成功', {'reload': True}) # 进行评分结束 if not is_head: raise Snap.error('不是社长') elif request.POST.get('star', ''): # 更改星级 try: star = int(request.POST.get('star', '')) except ValueError: raise Snap.error('内容不合法') performance.stars = star performance.data = 'preparing' performance.save() return Snap.success(request, '成功更改星级') else: # 提交数据 impact = [] for i in range(5): impact.append(request.POST.get('impact%d' % i, '')) if not all(impact): raise Snap.error('“影响力”没有填写全') star = AuthSnap.star_calc(cid) if performance.stars > star: raise Snap.error('星级太高') performance.extra = json.dumps(impact) performance.data = 'waiting' performance.save() PublicMessageAction.save(request, 'empty', 'new', cid, 'club', ClubSnap.cid_find_by_sname('club-union'), 'club') return Snap.success(request, '成功提交', {'redirect': '/auth/apply/'})
def funds_show(request, fid): '资金申请: 显示内容和调整状态' dict_render = UserAgentSnap.record(request) qry = AuthInfo.objects.filter(relation='funds', stars=fid) if not qry or qry[0].data == 'deleted': raise Http404() aid = qry[0].account_id if not aid: raise Http403('数据错误') is_union = AccountSnap.aid_verify \ (request, 'club', ClubSnap.cid_find_by_sname('club-union'), True, True) is_head = AccountSnap.aid_verify(request, 'club', aid) if not is_head and not is_union: raise Http403('您没有权限查看此页面') funds_form = AuthDicts.funds_form() # 和 dict_render['funds_form'] 不同 extra = json.loads(qry[0].extra) if request.method == 'POST': if not is_union: raise Snap.error('您没有权限更改状态') data = request.POST.get('data', '') if data not in ( 'granted', 'rejected', 'droped', ): raise Snap.error('参数错误') union_comment = request.POST.get('union_comment', '') if not union_comment: raise Snap.error('请输入反馈意见') if len(funds_form) + 2 < len(extra): # 有评论 extra[len(funds_form) + 2] = union_comment else: extra.append(union_comment) qry.update(data=data, extra=json.dumps(extra)) return Snap.success(request, '修改成功', {'reload': True}) dict_render['data'] = qry[0] dict_render['extra'] = extra status_translate = AuthDicts.funds_status_translate() dict_render['status'] = status_translate[qry[0].data] dict_render['funds_type'] = { 'funds': '社团发展基金', 'borrow': '社团借款', }[extra[1]] dict_render['funds_form'] = [] for i in range(len(funds_form)): dict_render['funds_form'].append(funds_form[i] + (extra[i + 2], )) if len(funds_form) + 2 < len(extra): # 有评论 dict_render['union_comment'] = extra[len(funds_form) + 2] dict_render['is_head'] = is_head dict_render['is_union'] = is_union head = ClubSnap.head_find_by_cid(aid) dict_render['head'] = head head_account = UserSnap.account_find_by_uid(head.id) dict_render['head_phone'] = head_account.phone dict_render['avatar'] = AvatarSnap.avatar_find('club', aid, 'raw') dict_render['head_grade'] = UserSnap.grade_translate \ (head_account.grade) dict_render['club'] = ClubSnap.club_find_by_cid(aid) fname = dict_render['club'].full_name dict_render['title'] = t_(' - 资金申请状态 - %s') % fname return Snap.render('funds_show.html', dict_render)
def thread_show(request, sname, thid): "显示单个帖子" dict_render = UserAgentSnap.record(request) try: thid = int(thid) except ValueError: raise Http404() group_qry = ForumSnap.group_find_by_sname(sname) if not group_qry: raise Http404() qry = ForumSnap.thread_find_by_thid(thid, group_qry.id) if not qry: raise Http404() if not ForumSnap.view_verify('thread', request, thid, group_qry.id): raise Http403('您没有权限查看本页面') dict_render['group_data'] = group_qry dict_render['thread_data'] = qry is_admin = ForumSnap.forum_admin_verify(request) or \ ForumSnap.group_admin_verify(request, qry.group_id) attach_list = ForumSnap.attach_wrap(qry.attach_uuid) dict_thread = { 'data': qry, 'relation': 'thread', 'level': 0, 'time_create': ChineseSnap.datetime_simp(qry.time_create), 'avatar': AvatarSnap.avatar_all(qry.send_relation, qry.send_id), 'nickname': UserSnap.nickname_find_by_uid(qry.send_id), 'sname': UserSnap.sname_find_by_uid(qry.send_id), 'attach': attach_list, 'attach_len': len(attach_list), 'attach_uuid': qry.attach_uuid, 'can_delete': is_admin or qry.send_id == request.user.id, } # 计算 response_list: 根据回复排序 response_qry = ForumSnap.response_find_by_thid(thid) \ .filter(reply_relation='thread') dict_render['response_list'] = [dict_thread] try: rid = int(request.GET.get('response', '0')) i = list(response_qry.values_list('id', flat=True)).index(rid) index = i // 10 + 1 except ValueError: index = None for i in AuthDicts.page_dict \ (request, response_qry, 10, dict_render, index) : children_list = [] for j in ForumSnap.response_find_by_thid(thid) \ .filter(reply_relation='response', reply_id=i.id) : children_list.append({ 'data': j, 'relation': 'response', 'time_create': ChineseSnap.datetime_simp(j.time_create), 'avatar': AvatarSnap.avatar_all(j.send_relation, j.send_id), 'nickname': UserSnap.nickname_find_by_uid(j.send_id), 'sname': UserSnap.sname_find_by_uid(j.send_id), 'can_delete': is_admin or j.send_id == request.user.id, }) dict_render['response_list'].append({ 'data': i, 'relation': 'response', 'level': 0, 'time_create': ChineseSnap.datetime_simp(i.time_create), 'avatar': AvatarSnap.avatar_all(i.send_relation, i.send_id), 'nickname': UserSnap.nickname_find_by_uid(i.send_id), 'sname': UserSnap.sname_find_by_uid(i.send_id), 'attach': attach_list, 'attach_len': len(attach_list), 'attach_uuid': i.attach_uuid, 'children_list': children_list, 'can_delete': is_admin or i.send_id == request.user.id, }) dict_render['thread_latest'] = ForumSnap.thread_latest_render() dict_render['title'] = t_(' - %s') % qry.subject return Snap.render('forum_thread.html', dict_render)
def thread_show(request, sname, thid): "显示单个帖子" dict_render = UserAgentSnap.record(request) try: thid = int(thid) except ValueError: raise Http404() group_qry = ForumSnapOld.group_find_by_sname(sname) if not group_qry: raise Http404() qry = ForumSnapOld.thread_find_by_thid(thid, group_qry.id) if not qry: raise Http404() if not ForumSnapOld.view_verify('thread', request, thid, group_qry.id): raise Http403('您没有权限查看本页面') dict_render['group_data'] = group_qry dict_render['thread_data'] = qry attach_list = ForumSnapOld.attach_wrap(qry.attach_uuid) dict_thread = { 'data': qry, 'relation': 'thread', 'level': 0, 'time_create': ChineseSnap.datetime_simp(qry.time_create), 'avatar': AvatarSnap.avatar_all(qry.send_relation, qry.send_id), 'nickname': UserSnap.nickname_find_by_uid(qry.send_id), 'sname': UserSnap.sname_find_by_uid(qry.send_id), 'attach': attach_list, 'attach_len': len(attach_list), 'attach_uuid': qry.attach_uuid, } # 计算 response_list: 根据回复排序 response_qry = ForumSnapOld.response_find_by_thid(thid) if request.GET.get('dependence') == 'true': def fetch_thread(level, src, aid): '将 response_list 中回复 src, aid 的条目采集出,然后递归' for i in response_list[:]: if level > recursive_limit: break if i.reply_relation != src or i.reply_id != aid: continue if i not in response_list: # should not happen logger.error('Error in fetch_thread. Thid = %d' % thid) response_sorted.append((level, i)) response_list.remove(i) fetch_thread(level + 1, 'response', i.id) response_sorted = [] response_list = list(response_qry) recursive_limit = len(response_list) fetch_thread(1, 'thread', thid) dict_render['dependence'] = True else: try: rid = int(request.GET.get('response', '0')) i = list(response_qry.values_list('id', flat=True)).index(rid) index = i // 10 + 1 except ValueError: index = None response_sorted = zip(itertools.repeat(0.5), AuthDicts.page_dict \ (request, response_qry, 10, dict_render, index)) dict_render['response_list'] = [dict_thread] # 第一个渲染帖子本身的内容 children_dict = {} # 用指针的作用,以提高效率 for level, i in response_sorted: # 附件 attach_list = ForumSnapOld.attach_wrap(i.attach_uuid) # 子回复 children_list = [] for j in response_qry.filter(reply_relation='response', reply_id=i.id).values_list('id', flat=True): if j not in children_dict: children_dict[j] = {} children_list.append(children_dict[j]) # 父回复 if i.reply_relation == 'response': if i.reply_id not in children_dict: children_dict[i.reply_id] = {} father = children_dict[i.reply_id] else: father = '' # 添加到 dict_render dict_render['response_list'].append({ 'data': i, 'relation': 'response', 'level': level, 'time_create': ChineseSnap.datetime_simp(i.time_create), 'avatar': AvatarSnap.avatar_all(i.send_relation, i.send_id), 'nickname': UserSnap.nickname_find_by_uid(i.send_id), 'sname': UserSnap.sname_find_by_uid(i.send_id), 'attach': attach_list, 'attach_len': len(attach_list), 'attach_uuid': i.attach_uuid, 'father': father, 'children_list': children_list, }) from quan_news.views import NewsSnap remove_space = lambda x: re.sub('\s+', ' ', x).strip() for i in response_qry.filter(id__in=children_dict): # 补全信息 extract_limit = 50 extracted = remove_space \ (' '.join(NewsSnap.content_extract(i.content))) if len(extracted) > extract_limit: extracted = extracted[:extract_limit] + ' ...' children_dict[i.id].update({ 'data': i, 'nickname': UserSnap.nickname_find_by_uid(i.send_id), 'sname': UserSnap.sname_find_by_uid(i.send_id), 'extracted': extracted, }) dict_render.update(ForumSnapOld.thread_latest_render()) dict_render['title'] = t_(' - %s') % qry.subject return Snap.render('forum_old_thread.html', dict_render)