async def set_status_balloon(domain_id: str, tid: int, uid: int, pid: int, balloon: bool = True): tdoc = await get(domain_id, tid) if pid not in tdoc['pids']: raise error.ValidationError('pid') coll = db.Collection('contest.status') tsdoc = await coll.find_one_and_update( filter={ 'domain_id': domain_id, 'tid': tid, 'uid': uid, 'detail.pid': pid }, update={'$set': { 'detail.$.balloon': balloon }}, return_document=ReturnDocument.AFTER) udoc = await user.get_by_uid(uid) await bus.publish( 'balloon_change', json.encode({ 'uid': uid, 'uname': udoc['uname'], 'nickname': udoc.get('nickname', ''), 'tid': tid, 'pid': pid, 'letter': convert_to_letter(tdoc['pids'], pid), 'balloon': balloon })) return tsdoc
async def stream_data(self, *, pid: int, headers_only: bool=False): pdoc = await problem.get(self.domain_id, pid) if (not self.own(pdoc, builtin.PERM_READ_PROBLEM_DATA_SELF) and not self.has_perm(builtin.PERM_READ_PROBLEM_DATA)): self.check_priv(builtin.PERM_READ_PROBLEM_DATA) grid_out = await problem.get_data(self.domain_id, pid) await self.binary(json.encode(grid_out['data']).encode('utf8'), 'application/json', filename='data_{0}.json'.format(pid)) """
def __iter__(self): try: self.response = web.Response() yield from HandlerBase.prepare(self) yield from super(Handler, self).__iter__() except error.UserFacingError as e: _logger.warning('User facing error: %s', repr(e)) self.response.set_status(e.http_status, None) if self.prefer_json: self.response.content_type = 'application/json' self.response.text = json.encode({'error': e.to_dict()}) else: self.render(e.template_name, error=e, page_name='error', page_title=self.translate('error'), path_components=self.build_path(self.translate('error'), None)) except Exception as e: _logger.error('Unexpected exception occurred when handling %s (IP = %s, UID = %d): %s', self.url, self.remote_ip, self.user['_id'] or None, repr(e)) raise return self.response
async def update(token_id: str, token_type: int, expire_seconds: int, replace: bool = False, **kwargs): """Update a token. Args: token_id: token ID. token_type: type of the token. expire_seconds: expire time, in seconds. replace: if True, replace this key instead of update. **kwargs: extra data. Returns: The token document, or None. """ db = await redis.database() assert 'token_type' not in kwargs now = datetime.datetime.utcnow() doc = await get(token_id, token_type) if not doc: return None if not replace: doc.update({ **kwargs, 'token_type': token_type, 'update_at': now, 'expire_at': now + datetime.timedelta(seconds=expire_seconds) }) else: doc = { **kwargs, 'token_type': token_type, 'update_at': now, 'expire_at': now + datetime.timedelta(seconds=expire_seconds) } await db.set('token_' + token_id, json.encode(doc), expire=expire_seconds) return doc
async def add(token_type: int, expire_seconds: int, **kwargs): """Add a token. Args: token_type: type of the token. expire_seconds: expire time, in seconds. **kwargs: extra data. Returns: Tuple of (Token ID, token document). """ id_binary = _get_id(os.urandom(32)) id_hash = binascii.hexlify(id_binary).decode() now = datetime.datetime.utcnow() doc = { **kwargs, '_id': id_hash, 'token_type': token_type, 'create_at': now, 'update_at': now, 'expire_at': now + datetime.timedelta(seconds=expire_seconds) } db = await redis.database() await db.set('token_' + id_hash, json.encode(doc), expire=expire_seconds) return id_hash, doc
async def update_status(domain_id: str, tid: int, uid: int, rid: objectid.ObjectId, pid: int, accept: bool): tdoc = await get(domain_id, tid) if pid not in tdoc['pids']: raise error.ValidationError('pid') coll = db.Collection('contest.status') tsdoc = await coll.find_one_and_update( filter={ 'domain_id': domain_id, 'tid': tid, 'uid': uid }, update={ '$push': { 'journal': { 'rid': rid, 'pid': pid, 'accept': accept } }, '$inc': { 'rev': 1 } }, return_document=ReturnDocument.AFTER) if not tsdoc: return {} if 'attend' not in tsdoc or not tsdoc['attend']: raise error.ContestNotAttendedError(domain_id, tid, uid) # Sort and uniquify journal of the contest status, by rid. key_func = lambda j: j['rid'] journal = [ list(g)[-1] for _, g in itertools.groupby(sorted(tsdoc['journal'], key=key_func), key=key_func) ] stats = RULES[tdoc['rule']].stat_func(tdoc, journal) psdict = {} for detail in tsdoc.get('detail', []): psdict[detail['pid']] = detail for detail in stats.get('detail', []): detail['balloon'] = psdict.get(detail['pid'], { 'balloon': False }).get('balloon', False) tsdoc = await coll.find_one_and_update( filter={ 'domain_id': domain_id, 'tid': tid, 'uid': uid }, update={ '$set': { 'journal': journal, **stats }, '$inc': { 'rev': 1 } }, return_document=ReturnDocument.AFTER) await bus.publish('contest_notification-' + str(tid), json.encode({'type': 'rank_changed'})) if accept and not psdict.get(pid, {'accept': False})['accept']: await set_status_balloon(domain_id, tid, uid, pid, False) return tsdoc
def send(self, **kwargs): super(Connection, self).send(json.encode(kwargs))
def json(self, obj): self.response.content_type = 'application/json' self.response.headers.add('Cache-Control', 'no-store, no-cache, must-revalidate') self.response.text = json.encode(obj)