async def delete(self, request): if request.username: database_name = hashlib.sha256( request.username.encode("utf-8")).hexdigest() else: raise exceptions.Unauthorized("A valid token is needed") data = await request.post() hash = data["hash"] file_path = storage.get_file(hash) dotfile_path = storage.get_file("." + hash) if not os.path.exists(file_path) or not os.path.exists(dotfile_path): raise exceptions.NotFound("file <{}> does not exist".format(hash)) with open(dotfile_path) as dotfile: dotfile_content = json.load(dotfile) user_dotfile_content = dotfile_content[database_name] spaces = user_dotfile_content["spaces"] storage.atto.Database(database_name).remove_data((hash, spaces)) if len(dotfile_content) == 1: os.remove(file_path) os.remove(dotfile_path) else: del dotfile_content[database_name] with open(dotfile_path, "w") as dotfile: json.dump(dotfile_content, dotfile) return web.json_response({"deleted": True})
def stats(self): try: data = requests.get( f"https://api.hypixel.net/player?key={self.api_key}&name={self.player}" ).json() except: raise exceptions.NotFound( "Either api key invalid or player name invalid!") self.display = data["player"]["displayname"] self.wins = data["player"]["achievements"]["bedwars_wins"] self.level = data["player"]["achievements"]["bedwars_level"] self.deaths = data["player"]["stats"]["Bedwars"]["deaths_bedwars"] self.kills = data["player"]["stats"]["Bedwars"]["kills_bedwars"] self.coins = data["player"]["stats"]["Bedwars"]["coins"] self.beds_lost = data["player"]["stats"]["Bedwars"][ "beds_lost_bedwars"] self.beds_destroyed = data["player"]["stats"]["Bedwars"][ "beds_broken_bedwars"] self.final_kills = data["player"]["stats"]["Bedwars"][ "final_kills_bedwars"] self.final_deaths = data["player"]["stats"]["Bedwars"][ "final_deaths_bedwars"] self.winstreak = data["player"]["stats"]["Bedwars"]["winstreak"] self.losses = data["player"]["stats"]["Bedwars"]["losses_bedwars"]
async def exception_middleware(request: web.Request, handler: Callable) -> web.Response: """ Обрабатывает исключения приложения :param request: объект запроса :param handler: обработчик :return: объект ответа """ try: response: web.Response = await handler(request) return response except MarshmallowValidationError as ex: exc = exceptions.ValidationError(debug=str(ex), message=exceptions.ValidationError.message) except exceptions.BaseAppException as ex: exc = ex except web_exceptions.HTTPBadRequest as ex: exc = exceptions.InputValidationError(debug=ex.text, message=exceptions.InputValidationError.message) except web_exceptions.HTTPUnprocessableEntity as ex: exc = exceptions.ValidationError(debug=ex.text, message=exceptions.ValidationError.message) except web_exceptions.HTTPForbidden as ex: exc = exceptions.Forbidden(debug=f'Goodbye Moonmen. {ex}', message=exceptions.Forbidden.message) except web_exceptions.HTTPNotFound as ex: exc = exceptions.NotFound(debug=ex.text, message=exceptions.NotFound.message) except Exception as ex: # pylint: disable=broad-except exc = exceptions.ServerError(debug=str(ex), message=exceptions.ServerError.message) exc_data = exc.as_dict() exc_data['message'] = exc.message exc_data.pop('code', None) exc.__init__(**exc_data) return web.json_response(exc.as_dict(), status=exc.status_code)
async def download(self, request): if request.username: database_name = hashlib.sha256( request.username.encode("utf-8")).hexdigest() else: raise exceptions.Unauthorized("A valid token is needed") data = await request.post() hash = data["hash"] file_path = storage.get_file(hash) dotfile_path = storage.get_file("." + hash) if not os.path.exists(file_path) or not os.path.exists(dotfile_path): raise exceptions.NotFound("file <{}> does not exist".format(hash)) with open(dotfile_path) as dotfile: dotfile_content = json.load(dotfile)[database_name] name = dotfile_content["name"] response = web.StreamResponse() response.headers["Content-Type"] = "application/octet-stream" response.headers[ "Content-Disposition"] = "attachment; filename*=UTF-8''{}".format( urllib.parse.quote(name, safe="") # replace with the filename ) response.enable_chunked_encoding() await response.prepare(request) with open(file_path, "rb") as fd: # replace with the path for chunk in iter(lambda: fd.read(1024), b""): await response.write(chunk) await response.write_eof() return response
def which_error(response): if response.status_code == 401: raise exceptions.AuthError() elif response.status_code == 500: raise Exception(response.text) elif response.status_code == 404: # Not in the group raise exceptions.NotFound()
def searchType(libtype): searchtypesstrs = [str(k) for k in SEARCHTYPES.keys()] if libtype in SEARCHTYPES + searchtypesstrs: return libtype stype = SEARCHTYPES.get(libtype.lower()) if not stype: raise exceptions.NotFound('Unknown libtype: %s' % libtype) return stype
def test_not_found(self): try: raise exceptions.NotFound(exceptions.NotFound.SONG, "test") except exceptions.NotFound as nf: assert nf.type == exceptions.NotFound.SONG assert nf.query == "test" except: assert False
def findResourceByID(resources, ID): """ Searches server.clientIdentifier """ util.LOG('Looking for server by ID: {0}'.format(ID)) for server in resources: if ID == server.clientIdentifier: util.LOG('Server found by ID: {0}'.format(server)) return server util.LOG('Unable to find server by ID: {0}'.format(ID)) raise exceptions.NotFound('Unable to find server by ID: {0}'.format(ID))
def findResource(resources, search, port=32400): """ Searches server.name """ search = search.lower() util.LOG('Looking for server: {0}'.format(search)) for server in resources: if search == server.name.lower(): util.LOG('Server found: {0}'.format(server)) return server util.LOG('Unable to find server: {0}'.format(search)) raise exceptions.NotFound('Unable to find server: {0}'.format(search))
def stats(self): try: data = requests.get( f"https://api.hypixel.net/player?key={self.api_key}&name={self.player}" ).json() except: raise exceptions.NotFound( "Either api key invalid or player name invalid!") self.firstLogin = data["player"]["firstLogin"] self.lastLogin = data["player"]["lastLogin"] self.namehistory = data["player"]["knownAliases"] self.display = data["player"]["displayname"]
def find(self, **kwargs): """ Find a single item with attributes matching ``**kwargs``. This isn't very efficient: it loads the entire list then filters on the Python side. """ rl = self.findall(**kwargs) try: return rl[0] except IndexError: msg = "No %s matching %s." % (self.resource_class.__name__, kwargs) raise exceptions.NotFound(404, msg)
def get_one(id_): """ Get one car :param id_: :return: """ db_data = database.find_document(auto_collection, {'_id': ObjectId(id_)}) if not db_data: raise exceptions.NotFound("Object not found") auto_obj = Auto() auto_obj.load_json(db_data) return auto_obj.serialize()
def get(cls, pkid_or_obj): """Returns an object matching the supplied ID. If the value is an instance of the object, verifies that the object's ID is valid. """ if isinstance(pkid_or_obj, cls): pkid = pkid_or_obj.pkid else: pkid = pkid_or_obj sql = "select * from {} where pkid = %s;".format(cls.table_name) with utils.DbCursor() as crs: crs.execute(sql, (pkid, )) rec = crs.fetchone() if not rec: raise exc.NotFound() # Allow subclasses to customize the response cls._after_get(rec) return cls(**rec)
async def exception_middleware( # pylint: disable=bad-continuation request: web.Request, handler: Callable[[web.Request], Awaitable[web.Response]], ) -> web.Response: # pylint: enable=bad-continuation """ Обрабатывает исключения приложения :param request: web.Request объект запроса :param handler: Coroutine[[web.Request], web.Response] обработчик :return: web.Response объект ответа """ exc: Optional[exceptions.ServerError] = None try: response: web.Response = await handler(request) except exceptions.ServerError as ex: exc = ex except MarshmallowValidationError as ex: exc = exceptions.ValidationError( debug=str(ex), message=exceptions.ValidationError.message) except web_exceptions.HTTPBadRequest as ex: exc = exceptions.InputValidationError( debug=ex.text, message=exceptions.InputValidationError.message) except web_exceptions.HTTPUnprocessableEntity as ex: exc = exceptions.ValidationError( debug=ex.text, message=exceptions.ValidationError.message) except web_exceptions.HTTPForbidden as ex: exc = exceptions.Forbidden(debug=f'Goodbye Moonmen. {ex}', message=exceptions.Forbidden.message) except web_exceptions.HTTPNotFound as ex: exc = exceptions.NotFound(debug=ex.text, message=exceptions.NotFound.message) except Exception as ex: # pylint: disable=broad-except exc = exceptions.ServerError(debug=str(ex), message=exceptions.ServerError.message) if not exc: return response exc_data = exc.as_dict() exc_data['message'] = exc.message exc_data.pop('code', None) type(exc)(**exc_data) return web.json_response(exc.as_dict(), status=exc.status_code)
def stats(self): try: data = requests.get( f"https://api.hypixel.net/player?key={self.api_key}&name={self.player}" ).json() except: raise exceptions.NotFound( "Either api key invalid or player name invalid!") self.display = data["player"]["displayname"] self.coins = data["player"]["stats"]["SkyWars"]["coins"] self.kills = data["player"]["stats"]["SkyWars"]["kills"] self.deaths = data["player"]["stats"]["SkyWars"]["deaths"] self.wins = data["player"]["stats"]["SkyWars"]["wins"] self.losses = data["player"]["stats"]["SkyWars"]["losses"] self.winstreak = data["player"]["stats"]["SkyWars"]["win_streak"] self.souls = data["player"]["stats"]["SkyWars"]["souls"] self.heads = data["player"]["stats"]["SkyWars"]["heads"]
async def exception_middleware( request: web.Request, handler: Callable[[web.Request], Awaitable[web.Response]], ) -> web.Response: sentry_event_id: Optional[str] = None try: response: web.Response = await handler(request) return response except MarshmallowValidationError as ex: exc: ServerError = exceptions.ValidationError(str(ex)) except web_exceptions.HTTPBadRequest as ex: exc = exceptions.InputValidationError(ex.text or '') except web_exceptions.HTTPUnprocessableEntity as ex: exc = exceptions.ValidationError(ex.text or '') except web_exceptions.HTTPForbidden as ex: exc = exceptions.Forbidden(str(ex)) except web_exceptions.HTTPNotFound as ex: exc = exceptions.NotFound(ex.text or '') except asyncio.CancelledError as ex: exc = exceptions.ServerError(str(ex)) except exceptions.ServerError as ex: exc = ex except NotImplementedError: exc = exceptions.MethodNotImplemented() # nolint except Exception as ex: # pylint: disable=W0703 print_exc() sentry_event_id = sentry_sdk.capture_exception(ex) exc = exceptions.ServerError(str(ex)) if not sentry_event_id: sentry_event_id = sentry_sdk.capture_exception(exc) return web.json_response(data=exc.as_dict(), status=exc.status_code, headers={'X-Sentry-ID': sentry_event_id or ''})
def determine_version(self, request, *args, **kwargs): version = request.query_params.get(self.version_param, self.default_version) if not self.is_allowed_version(version): raise exceptions.NotFound(self.invalid_version_message) return version
async def _rsvp_embed(self, bot, guild, rsvp=0, *, data=None): embed = discord.Embed(title='Raid Signup', color=0x3B6F4D) embed.set_footer(text='RSVP Bot © MattBSG 2020') if not isinstance(guild, discord.Guild): guild = bot.get_guild(guild) guild_doc = mclient.rsvpbot.config.find_one({'_id': guild.id}) if rsvp: doc = mclient.rsvpbot.reservations.find_one({'_id': rsvp}) if not doc: raise exceptions.NotFound('Reservation does not exist') leader = guild.get_member(doc['host']) if not leader: # Left, or uncached. Pull from api leader = await bot.fetch_user(doc['host']) user_aliases = {} user_db = mclient.rsvpbot.users alias_docs = user_db.find( {'_id': { '$in': [x['user'] for x in doc['participants']] }}) for x in alias_docs: user_aliases[x['_id']] = x['alias'] participants = [] for x in doc['participants']: user = guild.get_member(x['user']) if not user: # Left, or uncached. Pull from api user = await bot.fetch_user(x['user']) participants.append({ 'user': user, 'alias': None if not user.id in user_aliases else user_aliases[user.id], 'role': x['role'], 'status': x['status'] }) data = { 'date': pendulum.from_timestamp(doc['date'], tz=utility.timezone_alias( doc['timezone'])), 'timezone': doc['timezone'], 'description': doc['description'], 'host': leader, 'participants': participants } embed.description = f'{data["description"]}\n\n:man_raising_hand: {len(data["participants"])} Player{utility.plural(len(data["participants"]))} signed up\n' \ f':alarm_clock: Scheduled to start **{data["date"].format("MMM Do, Y at h:mmA")} {data["timezone"].capitalize()}**' tanks = [] healers = [] dps = [] for player in data['participants']: user = player status = user['status'] if user['alias']: user_alias = user['alias'] elif isinstance(user['user'], discord.Member): user_alias = user['user'].name if not user[ 'user'].nick else user['user'].nick else: user_alias = user['user'].name if status == 'confirmed' and data['host'].id == user['user'].id: status = 'host' if user['role'] == 'tank': tanks.append(constants.STATUS_MAPPING[status] + user_alias) elif user['role'] == 'healer': healers.append(constants.STATUS_MAPPING[status] + user_alias) else: dps.append(constants.STATUS_MAPPING[status] + user_alias) embed.add_field( name='Tanks', value='*No one yet*' if not tanks else '\n'.join(tanks), inline=True) embed.add_field( name='Healers', value='*No one yet*' if not healers else '\n'.join(healers), inline=True) embed.add_field(name='DPS', value='*No one yet*' if not dps else '\n'.join(dps), inline=True) embed.add_field(name='How to signup', value=f'To RSVP for this event please react below with the role you will ' \ f'be playing; {constants.EMOJI_TANK}Tank, {constants.EMOJI_HEALER}Healer, or {constants.EMOJI_DPS}DPS.\n' \ f'If you are not sure if you can make the event, react with your role as well as {constants.EMOJI_TENTATIVE}tentative. ' \ f'Expecting to be __late__ for the event? React with your role as well as {constants.EMOJI_LATE}late.\n\n' \ f'Should you want to unmark yourself as tentative or late simply react again. ' \ f'You may react {constants.EMOJI_CANCEL} to cancel your RSVP at any time. More information found in <#{guild_doc["info_channel"]}>' ) rsvp_channel = self.bot.get_channel(guild_doc['rsvp_channel']) if rsvp: try: message = await rsvp_channel.fetch_message(rsvp) await message.edit(embed=embed) except (discord.NotFound, discord.Forbidden): logging.error( f'[Main] Unable to fetch RSVP message {rsvp}, resending! Was it deleted?' ) message = await rsvp_channel.send(embed=embed) else: message = await rsvp_channel.send(embed=embed) return message
def findItem(server, path, title): for elem in server.query(path): if elem.attrib.get('title').lower() == title.lower(): return buildItem(server, elem, path) raise exceptions.NotFound('Unable to find item: {0}'.format(title))
def section(self, title=None): for item in self.sections(): if item.title == title: return item raise exceptions.NotFound('Invalid library section: %s' % title)