async def configure_errors(self, request: web.Request, handler: Callable) -> web.Response: try: return await handler(request) except web.HTTPException as ex: if ex.status == 404: self.logger.error(f"{self.API_NOT_IMPLEMENTED}: {request.path}") raise web.HTTPNotImplemented(text=self.API_NOT_IMPLEMENTED) if ex.status == 500: self.logger.error(f"{self.INTERNAL_SERVER_ERROR}: {request.path}") raise web.HTTPNotImplemented(text=self.INTERNAL_SERVER_ERROR) raise
async def handle(request: web.Request) -> web.Response: if not HAS_SCROLLPHAT: raise web.HTTPNotImplemented(text="No scrollphat :(") data = await request.text() await QUEUE.put(data) return web.Response(text="OK")
async def restore_backup(request): """ Restore from a backup :Example: curl -X PUT http://localhost:8081/foglamp/backup/1/restore """ raise web.HTTPNotImplemented( reason='Restore backup method is not implemented yet.') backup_id = request.match_info.get('backup_id', None) if not backup_id: raise web.HTTPBadRequest(reason='Backup id is required') try: backup_id = int(backup_id, 10) # TODO: FOGL-861 # restore = Restore(connect.get_storage()) # status = restore.restore_backup(backup_id) # return web.json_response({'status': status}) except ValueError: raise web.HTTPBadRequest(reason='Invalid backup id') except exceptions.DoesNotExist: raise web.HTTPNotFound( reason='Backup with {} does not exist'.format(backup_id)) except Exception as ex: raise web.HTTPException(reason=str(ex))
async def build_rrids_tree_view(app, tree_view_mode="std") -> Dict[str, Any]: if tree_view_mode != "std": raise web.HTTPNotImplemented( reason= "Currently only 'std' option for the classifiers tree view is implemented" ) scicrunch = SciCrunch.get_instance(app) repo = ResearchResourceRepository(app) flat_tree_view = {} for resource in await repo.list_resources(): try: validated_item = ClassifierItem( classifier=resource.rrid, display_name=resource.name.title(), short_description=resource.description, url=scicrunch.get_resolver_web_url(resource.rrid), ) node = validated_item.display_name.replace(":", " ") flat_tree_view[node] = validated_item except ValidationError as err: logger.warning( "Cannot convert RRID into a classifier item. Skipping. Details: %s", err) return Classifiers.construct(classifiers=flat_tree_view).dict( exclude_unset=True)
async def update_user(request): if request.is_auth_optional: _logger.warning(FORBIDDEN_MSG) raise web.HTTPForbidden # TODO: FOGL-1226 we don't have any user profile info yet except password, role raise web.HTTPNotImplemented(reason='FOGL-1226')
async def recommend(request): raise web.HTTPNotImplemented(text="TBD") #async def homepage(request): # async with request.app['db'].acquire() as conn: # cursor = await conn.execute(db.question.select()) # records = await cursor.fetchall() # questions = [dict(q) for q in records] # return {'questions': questions}
async def handle(request: web.Request) -> web.Response: if not HAS_GPIO: raise web.HTTPNotImplemented(text="No gpio :(") lights_on = await request.json() GPIO.output(17, bool(lights_on)) return web.Response(text="OK")
def _get_method(self, method): try: meth = getattr(self.model, method) except AttributeError: raise web.HTTPNotImplemented( reason="Not implemented by underlying model (loaded '%s')" % self.name) return meth
async def handle(request: web.Request) -> web.Response: if not HAS_SCROLLPHAT: raise web.HTTPNotImplemented(text="No scrollphat :(") brightness = await request.json() scrollphat.set_brightness(brightness) return web.Response(text="OK")
async def __call__(self, request): method = getattr(self, f'do_{request.method}', None) if method is None: raise web.HTTPNotImplemented() keys = request.path.rstrip('/').split('/')[1:] result = method(request, keys) if asyncio.iscoroutine(result): result = await result return result
def serialize(self, data): try: template.get_env(self.controller.request.app ).globals['controller'] = self.controller return template.render(self.controller._private.template, self.controller.request, data) except web.HTTPInternalServerError as e: if self.controller.request.is_ajax(): raise web.HTTPNotImplemented() else: raise e
def _catch_error(self): name = self.name try: yield except AttributeError: raise web.HTTPNotImplemented( reason=("Not implemented by underlying model (loaded '%s')" % name)) except NotImplementedError: raise web.HTTPNotImplemented( reason=("Model '%s' does not implement this functionality" % name)) except Exception as e: LOG.error("An exception has happened when calling method on " "'%s' model." % name) LOG.exception(e) if isinstance(e, web.HTTPException): raise e else: raise web.HTTPInternalServerError(reason=e)
async def credentials_info(self, request: web.Request): params = await request.json() cert_info_req = params.get('certInfo', False) # TODO implement certInfo # (biggest roadblock: asn1crypto doesn't implement RFC 4514) if cert_info_req: raise web.HTTPNotImplemented() try: cred_id = str(params['credentialID']) except KeyError: raise web.HTTPBadRequest() pki_arch, cert_spec = self._parse_credential_id(cred_id) cert = pki_arch.get_cert(cert_spec.label) subj_pub_key: keys.PublicKeyInfo = cert.public_key enabled = pki_arch.is_subject_key_available(cert_spec.label) key_info = { 'status': "enabled" if enabled else "disabled", 'algo': [ algos.SignedDigestAlgorithmId(algo).dotted for algo in ALGO_SUPPORT.get(subj_pub_key.algorithm, ()) ], 'len': subj_pub_key.bit_size, } if subj_pub_key.algorithm == 'ec': ec_params: keys.ECDomainParameters = \ subj_pub_key['algorithm']['parameters'] if ec_params.name == 'named': key_info['curve'] = ec_params.chosen.dotted certificates_req = params.get('certificates', 'single') if certificates_req not in ('none', 'chain', 'single'): raise web.HTTPBadRequest() response = {'key': key_info} if certificates_req != 'none': certs = [b64_der(cert)] if certificates_req == 'chain': certs.extend( b64_der(pki_arch.get_cert(ca_cert_lbl)) for ca_cert_lbl in pki_arch.get_chain(cert_spec.label)) response['cert'] = {'certificates': certs} response['authMode'] = 'implicit' service_params = self.service_params scal = "2" if service_params.hash_pinning_required else "1" response['SCAL'] = scal response['multisign'] = service_params.multisign return web.json_response(response)
def set_level_permissions(self): for level in ['public', 'private', 'authed']: try: level_perms = self.perms[level][self.operation] break except KeyError: level_perms = None if level_perms is None: # If it's private or authed request, and public access is possible, let it run raise web.HTTPNotImplemented( reason='Requested resource has no implemented access policy') self.request_type = level self.level_permissions = level_perms
async def posts(request: web.Request) -> web.Response: """ Обработчик get-запроса на адрес /posts Args: request: Данные запроса Returns: web.Response: ответ в формате json """ request_params = request.rel_url.query if not validate_params(request_params): raise web.HTTPNotImplemented(text='Not valid params!') res = await get_local_news(db=request.app['db_conn'], **request_params) return web.json_response(res)
async def resolve_did(request: web.BaseRequest): """Retrieve a did document.""" context: AdminRequestContext = request["context"] did = request.match_info["did"] try: session = await context.session() resolver = session.inject(DIDResolver) document = await resolver.resolve(context.profile, did) result = document.serialize() except DIDNotFound as err: raise web.HTTPNotFound(reason=err.roll_up) from err except DIDMethodNotSupported as err: raise web.HTTPNotImplemented(reason=err.roll_up) from err except ResolverError as err: raise web.HTTPInternalServerError(reason=err.roll_up) from err return web.json_response(result)
async def post(self) -> web.Response: name: str = self.request.match_info.get('name', "orders") event_access = create_event_access(self.request.app['DISTRIBUTOR_DB']) transaction = create_transaction(self.request.app['DISTRIBUTOR_DB']) try: event = await event_access.get_event_data( url=name, method=self.request.method) except IndexError: return web.HTTPNotImplemented() response: State = await transaction.receive(self.request, event) if response.code not in {200, 201}: log.warning(response.message) return web.Response(text=response.reason, status=response.code) response = await transaction.store() if response.code not in {200, 201}: log.warning(response.message) return web.Response(text=response.reason, status=response.code) return web.Response(text=transaction.message, status=201)
async def refresh_feature(self, feature, request: RequestRecord): """ Args: feature: the feature to be refreshed Todo: Schedule causally-independent features to be refreshed concurrently. This should just execute them serially. At some point in the near future, I'd like to implement a nice concurrent graph algorithm that lets the server keep multiple refreshes in flight at once. """ scheduled_features = await feature.expired_ancestors() try: for scheduled_feature in scheduled_features: record = CallRecord(scheduled_feature, request) await scheduled_feature.exec_feature(record) except errors.InstrumentNotFoundError as e: raise web.HTTPNotImplemented(reason=f"Instrument not found: {e}")
def wrap(*args, **kwargs): try: return f(*args, **kwargs) except NotImplementedError: raise web.HTTPNotImplemented( reason="Model does not implement this functionality")
def tape_library_handler_wrapper( request, action_name, required_params=None, optional_params=None, skip_lock_check=False, ): """This wrapper performs error handling for the API calls. Raises ------ Multiple exceptions see: https://docs.aiohttp.org/en/latest/web_exceptions.html """ # Check parameters if required_params is not None: for param in required_params: if param in request.query: if not request.query[param]: error = { "error": { "description": "empty parameter", "parameter": param, "reason": "empty", "type": "parameter", } } raise web.HTTPUnprocessableEntity(text=json.dumps(error)) else: error = { "error": { "description": "missing parameter", "parameter": param, "reason": "undefined", "type": "parameter", } } raise web.HTTPUnprocessableEntity(text=json.dumps(error)) library = request.app["tape_library"] # Check that library is not locked if not library.running and not skip_lock_check: error = { "error": { "description": "Library is locked", "reason": "locked", "type": "lock", } } raise web.HTTPForbidden(text=json.dumps(error)) # Check library queue if library.check_queue_max_depth_reached(): error = { "error": { "description": "to many requests in progress", "reason": "full", "type": "taskqueue", } } raise web.HTTPTooManyRequests(text=json.dumps(error)) # Check if action is available, run it, catch errors if any if hasattr(library, "action_" + action_name): try: data = getattr(library, "action_" + action_name)(**request.query) except web.HTTPException: raise except Exception as excpt: logging.exception(action_name) error = { "error": { "description": str(excpt), "reason": "internal", "type": "server", } } raise web.HTTPInternalServerError(text=json.dumps(error)) else: error = { "error": { "description": "no such method", "reason": "nosuch", "type": "method", } } raise web.HTTPNotImplemented(text=json.dumps(error)) return web.json_response(data)
async def not_implemented(): # 501 return web.HTTPNotImplemented()
def check_request(self, request): """ Add additional check for method implementation. """ super().check_request(request) method = request.method if not hasattr(self, method.lower()): raise web.HTTPNotImplemented('Missing implementation: %s' % method)
async def patch(self): if 'user_session' in self.request: return web.HTTPNotImplemented() return web.HTTPUnauthorized()
async def mediation_send_deny(_: web.Request): return web.HTTPNotImplemented( text="mediate-deny message not supported by AFGO.")
async def get_endpoint(self, resource: Optional[str] = None): raise web.HTTPNotImplemented( reason="No other action possible in twitter but authentication")
def bridge_disabled(self) -> web.HTTPException: return web.HTTPNotImplemented( **self._make_error("NET_MAUNIUM_BRIDGE_DISABLED", "This bridge is disabled in the manager"))
def _not_implemented_error(body): return web.HTTPNotImplemented(body=json.dumps(body).encode('utf-8'), content_type='application/json')
async def post(self): """ Creates a new task, just dumps whatever we have to the database after a brief format check { 'queue': 'foo', method': 'method.to.execute', 'args': (args), 'kwargs': {kwargs} } .. http:post:: / Gets a task from the dispatcher. If the table does not exist, it returns a 501 for the client to handle it **Example request**: .. sourcecode:: http POST / Host: example.com Accept: application/json, text/javascript { 'queue': 'foo', method': 'method.to.execute', 'args': (*args), 'kwargs': {**kwargs} } **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: text/javascript ok .. note:: method.to.execute must be a method importable in the workers' side :<json string queue: Queue (table) to add this task to :<json array args: List of positional arguments to pass to method :<json array kwargs: List of keyword arguments to pass to method :<json string method: Method to import and execute :statuscode 200: No error :statuscode 501: Table does not exist :statuscode 400: Not all params have been specified :statuscode 404: No more tasks in the queue, retry later """ opts = self.request.app['rethinkdb'] conn = await r.connect(**opts) await self.request.post() mandatory = ['queue', 'method'] if not all([a in self.request.POST for a in mandatory]): raise web.HTTPBadRequest() queue = r.db(opts['db']).table(self.request.POST['queue']) data = dict(self.request.POST) if 'args' not in data: data['args'] = [] if 'kwargs' not in data: data['kwargs'] = {} data.update({'status': TASK_PENDING}) try: id_ = await queue.insert(data).run(conn) except r.errors.ReqlOpFailedError as err: if 'does not exist.' in err.message: raise web.HTTPNotImplemented() raise web.HTTPNotFound('No more tasks') data.update({'id': id_['generated_keys'][0]}) return web.json_response(data)
async def update_transcript(request): return web.HTTPNotImplemented()
async def signatures_sign_hash(self, request: web.Request): params = await request.json() try: cred_id = str(params['credentialID']) sad = params['SAD'] except KeyError: raise web.HTTPBadRequest() csc_auth_obj = CSCAuthorization.verify_sad( sad, secret=self.service_params.sad_secret, credential_id=cred_id) pki_arch, cert_spec = self._parse_credential_id(cred_id) try: priv_key_info = pki_arch.key_set.get_private_key( cert_spec.subject_key) except ConfigurationError as e: raise web.HTTPBadRequest() try: hash_list = [base64.b64decode(x) for x in params['hash']] sign_algo_id = algos.SignedDigestAlgorithmId(params['signAlgo']) except (KeyError, ValueError): raise web.HTTPBadRequest() if csc_auth_obj.hashes is not None: if not set(hash_list).issubset(csc_auth_obj.hashes): raise web.HTTPBadRequest() else: if not len(hash_list) <= csc_auth_obj.num_signatures: raise web.HTTPBadRequest() sign_algo_params = params.get('signAlgoParams', None) if sign_algo_params is not None: if sign_algo_id.native != 'rsassa_pss': raise web.HTTPNotImplemented() try: sign_algo_params = algos.RSASSAPSSParams.load( base64.b64decode(sign_algo_params)) except ValueError: raise web.HTTPBadRequest() try: sign_algo = algos.SignedDigestAlgorithm({ 'algorithm': sign_algo_id, 'parameters': sign_algo_params }) except ValueError: raise web.HTTPBadRequest() hash_algo_oid = params.get('hashAlgo', None) try: hash_algo = sign_algo.hash_algo except ValueError: if hash_algo_oid is None: raise web.HTTPBadRequest() hash_algo = algos.DigestAlgorithmId(hash_algo_oid).native def _sign_hash(x): signed = generic_sign_prehashed(priv_key_info, x, sign_algo, digest_algorithm=hash_algo) return base64.b64encode(signed).decode('ascii') result = list(map(_sign_hash, hash_list)) return web.json_response({'signatures': result})