def user(uid: int) -> list: try: fopen = open(fields["fpuser"], "r") except: b = exceptions.NotFound() b.default_detail = "Bad user file path" raise b for line in fopen.read().splitlines(): f = line.split(":") if (int(f[2]) == uid): f.pop(1) ##removes password field return [dict(zip(userf, f))] raise exceptions.NotFound() ##Returns with HTTP Status 404
def group(gid: int) -> list: try: fopen = open(fields["fpgroup"], "r") except: b = exceptions.NotFound() b.default_detail = "Bad group file path" raise b for line in fopen.read().splitlines(): f = line.split(":") if (int(f[2]) == gid): f[-1] = f[-1].split(",") #Only necessary upon pattern match f.pop(1) #removes password field return [dict(zip(groupf, f))] raise exceptions.NotFound() ##Returns with HTTP Status 404
def get_user(app: App, user_id: int) -> dict: if user_id not in USERS: raise exceptions.NotFound() return { 'username': USERS[user_id], 'url': app.reverse_url('get_user', user_id=user_id) }
def lookup(self, path: str, method: str) -> HandlerLookup: lookup_key = method + ' ' + path try: return self._lookup_cache[lookup_key] except KeyError: pass try: name, kwargs = self._adapter.match(path, method) except werkzeug.exceptions.NotFound: raise exceptions.NotFound() from None except werkzeug.exceptions.MethodNotAllowed: raise exceptions.MethodNotAllowed() from None except werkzeug.routing.RequestRedirect as exc: path = urlparse(exc.new_url).path raise exceptions.Found(path) from None view = self._views[name] self._lookup_cache[lookup_key] = (view, kwargs) if len(self._lookup_cache) > self._lookup_cache_size: self._lookup_cache.pop(next(iter( self._lookup_cache))) # pragma: nocover return (view, kwargs)
def resolve(self, parameter: inspect.Parameter, path_params: ValidatedPathParams, query_params: ValidatedQueryParams): params = path_params if (parameter.name in path_params) else query_params has_default = parameter.default is not parameter.empty allow_null = parameter.default is None param_validator = { parameter.empty: validators.Any(), str: validators.String(allow_null=allow_null), int: validators.Integer(allow_null=allow_null), float: validators.Number(allow_null=allow_null), bool: validators.Boolean(allow_null=allow_null) }[parameter.annotation] validator = validators.Object( properties=[(parameter.name, param_validator)], required=[] if has_default else [parameter.name]) try: params = validator.validate(params, allow_coerce=True) except validators.ValidationError as exc: raise exceptions.NotFound(exc.detail) return params.get(parameter.name, parameter.default)
def get_id(p: http.QueryParam, name: str) -> dict: _auth(p) response = redisclient.get_id(name) if response is None: raise exceptions.NotFound() else: return json.loads(response)
async def delete_article(article_id: int, password: http.Header): # if not is_auth(password): # raise exceptions.BadRequest() try: repo.delete_article(article_id) except LookupError: raise exceptions.NotFound() return http.Response('', status_code=204)
def build(cls, args: URLPathArgs, arg_name: ArgName): value = args.get(arg_name) if cls.schema is not None and not isinstance(value, cls.schema): try: value = cls.schema(value) except exceptions.SchemaError: raise exceptions.NotFound() return value
def lookup(self, path: str, method: str) -> RouterLookup: try: (name, kwargs) = self.adapter.match(path, method) except werkzeug.exceptions.NotFound: raise exceptions.NotFound() except werkzeug.exceptions.MethodNotAllowed: raise exceptions.MethodNotAllowed() (view, pipeline) = self.views[name] return (view, pipeline, kwargs)
def delete_id(p: http.QueryParam, name: str) -> dict: _auth(p) response = redisclient.get_id(name) if response is None: raise exceptions.NotFound() if not redisclient.delete_id(name): raise exceptions.HTTPException( 'Internal error while deleting ' + 'identity {}'.format(name), 500) return {'deleted': name}
def serve_static(statics: StaticFiles, path: PathWildcard, method: http.Method, headers: http.Headers, file_wrapper: FileWrapper) -> Response: static_file = statics.get_file(path) if static_file is None: raise exceptions.NotFound() return static_file.get_response(method, headers, file_wrapper)
def get_or_404(self, *args, **kwargs): """ Get a document and raise a 404 Not Found error if it doesn't exist. """ try: return self.get(*args, **kwargs) except (MultipleObjectsReturned, DoesNotExist, ValidationError): # TODO: probably only DoesNotExist should raise a 404 raise exceptions.NotFound()
def first_or_404(self, *args, **kwargs): """ Same as get_or_404, but uses .filter().first, not .get. """ queryset = self.filter(*args, **kwargs) if not queryset: raise exceptions.NotFound() return queryset.first()
def _find_service(id): """ Find a service by id """ service = Service.find(id) if not service: msg = f"Service not found" raise exceptions.NotFound({"services": msg})
async def update_article(article_id: int, data: http.RequestData, password: http.Header): # if not is_auth(password): # raise exceptions.BadRequest() if not data['title']: raise exceptions.BadRequest() try: repo.update_article(article_id, data['title']) except LookupError: raise exceptions.NotFound()
def get_service(id): """ Get service information """ service = Service.find(id) if not service: msg = f"Service not found." raise exceptions.NotFound({"message": msg}) return service.serialize()
def get_user(id): """ Get user information """ user = User.find(id) if not user: msg = f"User not found." raise exceptions.NotFound({"message": msg}) return user.serialize()
def __init__(self, iterable, page, per_page): if page < 1: raise exceptions.NotFound() self.iterable = iterable self.page = page self.per_page = per_page if isinstance(iterable, QuerySet): self.total = iterable.count() else: self.total = len(iterable) start_index = (page - 1) * per_page end_index = page * per_page self.items = iterable[start_index:end_index] if isinstance(self.items, QuerySet): self.items = self.items.select_related() if not self.items and page != 1: raise exceptions.NotFound()
def _find_feature(id): """ Find a feature by id """ feature = Feature.find(id) if not feature: msg = f"Feature not found." raise exceptions.NotFound({"message": msg}) return feature
def lookup(self, path: str, method: str) -> RouterLookup: try: (name, kwargs) = self.adapter.match(path, method) except werkzeug.exceptions.NotFound: raise exceptions.NotFound() except werkzeug.exceptions.MethodNotAllowed: raise exceptions.MethodNotAllowed() except werkzeug.routing.RequestRedirect as exc: path = urlparse(exc.new_url).path raise exceptions.Found(path) (view, pipeline) = self.views[name] return (view, pipeline, kwargs)
def ulist() -> list: try: fopen = open(fields["fpuser"], "r") except: b = exceptions.NotFound() b.default_detail = "Bad user file path" raise b retlist = [] for line in fopen.read().splitlines(): f = line.split(":") f.pop(1) #removes password field retlist.append(dict(zip(userf, f))) return retlist
def resolve(parameter: Parameter, params_dict): try: value = params_dict[parameter.name] except KeyError: if parameter.default is not parameter.empty: return parameter.default else: raise exceptions.NotFound( f"Parameter {parameter.name} not resolved") try: return parameter.annotation(value) except Exception: raise exceptions.BadRequest(f"Parameter {parameter.name} invalid")
def glist(mname: str = None) -> list: ##optional param to check for a member try: fopen = open(fields["fpgroup"], "r") except: b = exceptions.NotFound() b.default_detail = "Bad group file path" raise b retlist = [] for line in fopen.read().splitlines(): f = line.split(":") f[-1] = f[-1].split(",") if (mname and not mname in f[-1]): continue f.pop(1) retlist.append(dict(zip(groupf, f))) return retlist
def resolve(self, route: Route, path_params: http.PathParams) -> ValidatedPathParams: path_fields = route.link.get_path_fields() validator = validators.Object( properties=[(field.name, field.schema if field.schema else validators.Any()) for field in path_fields], required=[field.name for field in path_fields]) try: path_params = validator.validate(path_params, allow_coerce=True) except validators.ValidationError as exc: raise exceptions.NotFound(exc.detail) return ValidatedPathParams(path_params)
def delete_user(id): """ Delete a user """ user = User.find(id) if not user: msg = f"User not found." raise exceptions.NotFound({"message": msg}) user.delete() msg = "User deleted successfully." log.info(f"{msg} - ID: {id}") return {"message": msg}
def delete_service(id): """ Delete a service """ service = Service.find(id) if not service: msg = f"Service not found." raise exceptions.NotFound({"message": msg}) service.delete() msg = "Service deleted successfully." log.info(f"{msg} - ID: {id}") return {"message": msg}
def update_user(userData: UserType, id): """ Update user information """ user = User.find(id) if not user: msg = f"User not found." raise exceptions.NotFound({"message": msg}) user.update(**userData) msg = "User update successfully." log.info(f"{msg} - ID: {id}") return {"message": msg}
def url_argument(self, name: ParamName, kwargs: KeywordArgs, coerce: ParamAnnotation) -> typing.Any: value = kwargs[name] if value is None or isinstance(value, coerce): return value try: return coerce(value) except exceptions.TypeSystemError as exc: detail = {name: exc.detail} except (TypeError, ValueError) as exc: detail = {name: str(exc)} raise exceptions.NotFound(detail=detail)
def serve_static(path: Path, statics: Statics, environ: wsgi.WSGIEnviron) -> wsgi.WSGIResponse: if not path.startswith('/'): path = Path('/' + path) static_file = statics.whitenoise.files.get(path) if static_file is None: raise exceptions.NotFound() response = static_file.get_response(environ['REQUEST_METHOD'], environ) status_line = '{} {}'.format(response.status, response.status.phrase) headers = list(response.headers) if response.file is not None: file_wrapper = environ.get('wsgi.file_wrapper', FileWrapper) content = file_wrapper(response.file) else: # We hit this branch for HEAD requests content = [] return wsgi.WSGIResponse(status_line, headers, content)
def login(self, username, password): """ comprueba usuario y contraseña y retorna un token con tiempo de expiracion """ user = self.users.find_one({'username': username}) if user: ph = PasswordHasher() try: if ph.verify(user['password'], password): exp = datetime.utcnow() + timedelta(hours=EXPIRY_TIME) token = jwt.encode(payload={'user': str(user['_id']), 'exp': exp}, key=SECRET_KEY) return {'token': token.decode('UTF-8')} except VerifyMismatchError: raise exceptions.BadRequest('Incorrect password') raise exceptions.NotFound('User not found')