def paginate(self, page, per_page, error_out=True): """Returns `per_page` items from page `page`. By default it will abort with 404 if no items were found and the page was larger than 1. This behavor can be disabled by setting `error_out` to `False`. If page or per_page are None, they will be retrieved from the request query. If the values are not ints and ``error_out`` is true, it will abort with 404. If there is no request or they aren't in the query, they default to page 1 and 20 respectively. Returns an :class:`Pagination` object. """ if error_out and page < 1: raise NotFound() items = self.limit(per_page).offset((page - 1) * per_page).all() if not items and page != 1 and error_out: raise NotFound() # No need to count if we're on the first page and there are fewer # items than we expected. if page == 1 and len(items) < per_page: total = len(items) else: total = self.order_by(None).count() return Pagination(self, page, per_page, total, items)
def get_note(note_id): note = Note.get(note_id) if not note: raise NotFound() visitor = utils.get_visitor() if note.hidden and not visitor.is_me: raise NotFound() return note.note
def find_matching_url(request): """ Определяет есть ли метод запроса в REQUEST_MAPPINGS """ if request.method not in REQUEST_MAPPINGS: raise NotFound("The HTTP request method '%s' is not supported." % request.method) for url_set in REQUEST_MAPPINGS[request.method]: match = url_set[0].search(request.path) if match is not None: return url_set, match.groupdict() raise NotFound("Sorry, nothing here.")
def static_file(filename, root=MEDIA_ROOT): """ Выдает статический файл из файловой системы, указанной в MEDIA_ROOT. """ if filename is None: raise Forbidden("You must specify a file you'd like to access.") valid_path = filename.strip('/') valid_path = valid_path.replace('//', '/').replace('/./', '/').replace('/../', '/') desired_path = os.path.join(root, valid_path) if not os.path.exists(desired_path): raise NotFound("File does not exist.") if not os.access(desired_path, os.R_OK): raise Forbidden("You do not have permission to access this file.") ct = str(content_type(desired_path)) if ct.startswith('text') or ct.endswith('xml') or ct.endswith('json'): return open(desired_path, 'r').read() return open(desired_path, 'rb').read()
def handle_http(self, ctx): name = ctx.shift() if name is not None: raise NotFound(ctx, name, self) # No traversal to subobjects! method = ctx.environ['REQUEST_METHOD'].upper() if method not in ('GET', 'HEAD'): raise UnsupportedMethod(ctx) if clientHas(self.lastModified, self.ETag): return '304 Not Modified', [], [] # XXX test this stream, size = self.getStreamAndSize() def dump_data(): if method == 'GET': # HEAD doesn't need the data size = self.blocksize while 1: data = stream.read(size) if not data: break yield data stream.close() headers = [('Content-Length', str(size))] if self.mime_type: headers.append(('Content-Type', self.mime_type)) return '200 OK', headers, dump_data()
def challenge_summary(self, category): if len(self.challenges) == 0: raise NotFound( "No challenges found. Add one with `>challenge add <name> <category>`" ) solved_response, unsolved_response = "", "" challenges = self.challenges if category and category != 'all': challenges = filter(lambda c: category in c.tags, challenges) challenges = sorted(challenges, key=lambda c: (c.tags, c.name, c.solved_at or c.created_at)) for challenge in challenges: chal_hash = self.get_chal_hash(challenge.name) challenge_details = f'[{chal_hash} :: {challenge.name}]' notes_url = f'[notes]({challenge.notebook_url})' flag = f'{{{challenge.flag or ""}}}' tags = ",".join(challenge.tags) if challenge.solved_at: solved_response += f'> {challenge_details}({tags}) <{",".join(challenge.solved_by)}> {flag}\n' else: if len(challenge.working_on) > 0: unsolved_response += f'* {challenge_details}({tags}) <{",".join(challenge.working_on)}> {flag}\n' else: unsolved_response += f'< {challenge_details}({tags}) < -- > {flag}\n' return solved_response, unsolved_response
def __call__(self, environ, start_response, exc_info=None): request, response = self.getRequestResponse(environ) try: req = Request(request, response) v = self.send(req, "request", self.channel, errors=True) if v: if issubclass(type(v), basestring): response.body = v res = Response(response) self.send(res, "response", self.channel) elif isinstance(v, HTTPError): self._handleError(v) elif isinstance(v, wrappers.Response): res = Response(v) self.send(res, "response", self.channel) else: assert v, "type(v) == %s" % type(v) else: error = NotFound(request, response) self._handleError(error) except: error = HTTPError(request, response, 500, error=format_exc()) self._handleError(error) finally: body = response.process() start_response(response.status, response.headers.items(), exc_info) return [body]
def get_challenge(self, name): challenge = next( (c for c in self.challenges if c.name == name or self.get_chal_hash(c.name) == name), None) if not challenge: raise NotFound("Challenge not found.") return challenge
def get_content(file_name: Path): if not file_name.is_file(): raise NotFound() with file_name.open("r", encoding="utf-8") as fp: content = fp.read() return content
def delete(self): if self._id is None: raise NotFound(self.fqdn) url = Zerigo._url_api + Host._url_delete.substitute(host_id=self._id) Zerigo._logger.debug('deleting ' + url + ' (' + self.fqdn + ')') self._conn.delete(url) self._id = None
def get_user(username): user = User.get_user(username) if user is None: raise NotFound(username) user_dict = user.user_dict del user_dict['hashed_password'] del user_dict['salt'] return user_dict
def first_or_404(self): """Like :meth:`first` but aborts with 404 if not found instead of returning `None`. """ rv = self.first() if rv is None: raise NotFound() return rv
def get_or_404(self, ident): """Like :meth:`get` but aborts with 404 if not found instead of returning `None`. """ rv = self.get(ident) if rv is None: raise NotFound() return rv
def get_picture(file_name: Path): if not file_name.is_file(): raise NotFound() with file_name.open("rb") as picture: image = picture.read() return image
def delete_user(username): user = User.get_user(username) if user is None: raise NotFound(username) if user.delete(): return util.success_response() else: raise Exception('deletion failed')
def select_entry(self, entries, format, attrs, display_count=True): """ Display a list of lines in with formatting defined in ``format``. ``attrs`` is a list of attributes in the format. Prompt user for a selection and return the value (index of ``entries`` -1). If only one entry is provided then always return 0. Return: 0..n for the index of the selected entry -1 if all entries should be displayed -2 to quit, no entries to be displayed """ if not self.env.interactive or not sys.stdout.isatty(): return -1 counter = len(entries) if counter == 0: raise NotFound(reason=_("No matching entries found")) i = 1 for e in entries: # There is no guarantee that all attrs are in any given # entry d = {} for a in attrs: d[a] = e.get(a, '') self.print_line("%d: %s" % (i, format % d)) i = i + 1 if display_count: self.print_count(entries, 'Found %d match', 'Found %d matches') while True: try: resp = self.prompt( "Choose one: (1 - %s), a for all, q to quit" % counter) except EOFError: return -2 if resp.lower() == "q": #pylint: disable=E1103 return -2 if resp.lower() == "a": #pylint: disable=E1103 return -1 try: selection = int(resp) - 1 if (selection >= 0 and selection < counter): break except: # fall through to the error msg pass self.print_line("Please enter a number between 1 and %s" % counter) self.print_line('') return selection
def _get_ctf(self, ctx: commands.Context, ctf_name = None): if ctf_name: try: return CTFModel.objects.get({'guild_id': ctx.guild.id, 'name': ctf_name}) except CTFModel.DoesNotExist: raise NotFound(f"No CTF named `{ctf_name}` found.\nRun `>ctf create [ctf-name]` to create a new ctf") elif isinstance(ctx.message.channel, discord.TextChannel): try: category_id = ctx.message.channel.category_id return CTFModel.objects.get({'guild_id': ctx.guild.id, 'category_id': category_id}) except CTFModel.DoesNotExist: raise NotFound("No CTF found in channel.\nRun `>ctf create [ctf-name]` to create a new ctf") elif isinstance(ctx.message.channel, discord.DMChannel): member = self._get_member(ctx.message.author.id) if not member: raise Exception("You are not a member of any ctfs.") if not member.current_ctf: raise Exception("You haven't set an active ctf. Run `>setctf`") return member.current_ctf
def handle(self, event): # Extract route method route = self.routes.get(event.route_key) # Raise 404 NOT FOUND if bad route if route is None: raise NotFound(f"No route defined for '{ event.route_key }'") # Execute request return route(event)
def read_static(path: str) -> bytes: static = settings.STATIC_DIR / path if not static.is_file(): full_path = static.resolve().as_posix() msg = f"file <{full_path}> not found" raise NotFound(msg) with static.open("rb") as fp: result = fp.read() return result
def delete(self): if (self._id is None): raise NotFound(self.name) url = Zerigo._url_api + Zone._url_delete.substitute(zone_id=self._id) Zerigo._logger.debug('deleting ' + url + ' (' + self.name + ')') # will raise an exception in case of problem. Maybe we should at least # check for a 404 to be consistent by throwing a zerigo.NotFound ? # And to be consistent with create which catch restkit.RequestFailed. self._conn.delete(url) self._id = None # reset the id, the zone no longer exists
def read_content(path: str): static_obj = project_dir / path if not static_obj.is_file(): static_path = static_obj.resolve().as_posix() err_msg = f"file <{static_path}> not found" raise NotFound(err_msg) with static_obj.open("rb") as src: content = src.read() return content
def put_note(note_id): data = request.json if not data: raise Error('note required') note = Note.get(note_id) if not note: raise NotFound() data.pop('id', None) note.note.update(data) if note.save(): return note.note
def read_static(path: str) -> bytes: static_obj = settings.STATIC_DIR / path if not static_obj.is_file(): static_path = static_obj.resolve().as_posix() err_msg = f"file <{static_path}> not found" raise NotFound(err_msg) with static_obj.open("rb") as src: content = src.read() return content
def multimerge(doc, merged_keys, merged_node=None): merged_doc = {} merged_node = merged_node or 'merged_' + '_'.join(merged_keys) for k in merged_keys: if k not in doc: raise NotFound('Key %s not found in document' % (repr(k))) doc_k = doc[k] merged_doc = doc_merge(doc_k, merged_doc, conventional_strategy) merged_doc = {merged_node: merged_doc} for k, v in doc.iteritems(): if k not in merged_keys: merged_doc.update({k: v}) return merged_doc, merged_node
def put_user_info(username): visitor = util.get_visitor() if not visitor or visitor['username'] != username: raise Error('you are not {}'.format(username)) user = User.get_user(username) if user is None: raise NotFound(username) user_dict_patch = request.json if not user_dict_patch: raise Error('empty update') if user.update(user_dict_patch): return util.success_response() else: raise Error('update failed')
def SendMailTo(self, receiver_id, title, content, signature_id, session, save_in_sent): receiver = UserManager.UserManager.LoadUser(receiver_id) if receiver is None: raise NotFound("no such user '%s'" % receiver_id) if not self.MayMailTo(receiver): raise NoPerm("no permission") # not reachable header = Post.Post.PrepareHeaderForMail(self, title, session) signature = Util.gbkDec(self.GetSig(signature_id)) content = header + content + signature self.MailTo(receiver, title, content, save_in_sent)
def find_obj(base, path): """ Find and return attribute at base.<path> where path is a dot seperated path to some attribute Raise NotFound if can't find the attribute """ obj = base found = [] parts = path.split(".") for part in parts: if not hasattr(obj, part): raise NotFound(path=path, base=base, found=found) obj = getattr(obj, part) found.append(part) return obj
def read_static(path: str) -> bytes: """ Reads and returns the content of static file. If there is no file, then NotFound exception is raised. :param path: path to static content :return: bytes of content """ static_obj = settings.STATIC_DIR / path if not static_obj.is_file(): static_path = static_obj.resolve().as_posix() err_msg = f"file <{static_path}> not found" raise NotFound(err_msg) with static_obj.open("rb") as src: content = src.read() return content
def get_file_response(self, path, request): try: if not isinstance(path, basestring): path = '/'.join(path) full_path = find_file(self.search_paths, path) if full_path is None: raise NotFound(is_breaking=False) except (ValueError, IOError, OSError): raise Forbidden(is_breaking=False) bfr = build_file_response resp = bfr(full_path, cache_timeout=self.cache_timeout, cached_modify_time=request.if_modified_since, mimetype=None, default_text_mime=self.default_text_mime, default_binary_mime=self.default_binary_mime, file_wrapper=request.environ.get('wsgi.file_wrapper', FileWrapper)) return resp
def build_file_response(path, cache_timeout=None, cached_modify_time=None, mimetype=None, default_text_mime=DEFAULT_TEXT_MIME, default_binary_mime=DEFAULT_BINARY_MIME, file_wrapper=FileWrapper, response_type=Response): resp = response_type('') if cache_timeout and cached_modify_time: try: mtime = get_file_mtime(path) except (ValueError, IOError, OSError): # TODO: winnow this down raise Forbidden(is_breaking=False) resp.cache_control.public = True if mtime <= cached_modify_time: resp.status_code = 304 resp.cache_control.max_age = cache_timeout return resp if not isfile(path): raise NotFound(is_breaking=False) try: file_obj = open(path, 'rb') mtime = get_file_mtime(path) fsize = os.path.getsize(path) except (ValueError, IOError, OSError): raise Forbidden(is_breaking=False) if not mimetype: mimetype, encoding = mimetypes.guess_type(path) if not mimetype: peeked = peek_file(file_obj, 1024) is_binary = is_binary_string(peeked) if peeked and is_binary: mimetype = default_binary_mime else: mimetype = default_text_mime resp.response = file_wrapper(file_obj) resp.content_type = mimetype resp.content_length = fsize resp.last_modified = mtime resp.cache_control.max_age = cache_timeout return resp