async def post(self): # Check usage before handle upload. quota = self.get_quota() usage = await userfile.get_usage(self.user['_id']) if usage >= quota: raise error.UsageExceededError('system', self.user['_id'], 'usage_userfile', usage, quota) fields = collections.OrderedDict([('desc', '')]) file_id = await handle_file_upload(self, fields) fdoc = await fs.get_meta(file_id ) # TODO(twd2): join from handle_file_upload # Check usage after handled upload. dudoc = None try: dudoc = await userfile.inc_usage(self.user['_id'], fdoc['length'], quota) except: await fs.unlink(file_id) raise usage = dudoc['usage_userfile'] ufid = await userfile.add(fields['desc'], file_id, self.user['_id'], fdoc['length']) self.render('fs_upload.html', fdoc=fdoc, ufid=ufid, usage=usage, quota=quota)
async def inc_user_usage(domain_id: str, uid: int, usage_field: str, usage: int, quota: int): coll = db.coll('domain.user') try: return await coll.find_one_and_update(filter={'domain_id': domain_id, 'uid': uid, usage_field: {'$not': {'$gte': quota - usage}}}, update={'$inc': {usage_field: usage}}, upsert=True, return_document=ReturnDocument.AFTER) except errors.DuplicateKeyError: raise error.UsageExceededError(domain_id, uid, usage_field, usage, quota)