Python aiohttp.web.HTTPBadRequest() Examples
The following are 30
code examples of aiohttp.web.HTTPBadRequest().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
aiohttp.web
, or try the search function
.
Example #1
Source File: http_charfinder2.py From example-code with MIT License | 6 votes |
def get_chars(request): peername = request.transport.get_extra_info('peername') print('Request from: {}, GET data: {!r}'.format(peername, dict(request.GET))) query = request.GET.get('query', '') if query: try: start = int(request.GET.get('start', 0)) stop = int(request.GET.get('stop', sys.maxsize)) except ValueError: raise web.HTTPBadRequest() stop = min(stop, start+RESULTS_PER_REQUEST) num_results, chars = index.find_chars(query, start, stop) else: raise web.HTTPBadRequest() text = ''.join(char if n % 64 else char+'\n' for n, char in enumerate(chars, 1)) response_data = {'total': num_results, 'start': start, 'stop': stop} print('Response to query: {query!r}, start: {start}, stop: {stop}'.format( query=query, **response_data)) response_data['chars'] = text json_obj = json.dumps(response_data) print('Sending {} characters'.format(len(text))) headers = {'Access-Control-Allow-Origin': '*'} return web.Response(content_type=TEXT_TYPE, headers=headers, text=json_obj)
Example #2
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def rotate_public_did_keypair(request: web.BaseRequest): """ Request handler for rotating key pair associated with public DID. Args: request: aiohttp request object """ context = request.app["request_context"] ledger = await context.inject(BaseLedger, required=False) if not ledger: reason = "No ledger available" if not context.settings.get_value("wallet.type"): reason += ": missing wallet-type?" raise web.HTTPForbidden(reason=reason) async with ledger: try: await ledger.rotate_public_did_keypair() # do not take seed over the wire except (WalletError, BadLedgerRequestError) as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({})
Example #3
Source File: test_routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def test_publish_registry_x(self): REV_REG_ID = "{}:4:{}:3:CL:1234:default:CL_ACCUM:default".format( self.test_did, self.test_did ) request = async_mock.MagicMock() request.app = self.app request.match_info = {"rev_reg_id": REV_REG_ID} with async_mock.patch.object( test_module, "IndyRevocation", autospec=True ) as mock_indy_revoc: mock_indy_revoc.return_value = async_mock.MagicMock( get_issuer_rev_reg_record=async_mock.CoroutineMock( return_value=async_mock.MagicMock( publish_registry_definition=async_mock.CoroutineMock( side_effect=test_module.RevocationError() ), ) ) ) with self.assertRaises(test_module.web.HTTPBadRequest): await test_module.publish_registry(request)
Example #4
Source File: rest_svc.py From caldera with Apache License 2.0 | 6 votes |
def update_operation(self, op_id, state=None, autonomous=None, obfuscator=None): async def validate(op): try: if not len(op): raise web.HTTPNotFound elif await op[0].is_finished(): raise web.HTTPBadRequest(body='This operation has already finished.') elif state not in op[0].states.values(): raise web.HTTPBadRequest(body='state must be one of {}'.format(op[0].states.values())) except Exception as e: self.log.error(repr(e)) operation = await self.get_service('data_svc').locate('operations', match=dict(id=op_id)) if state: await validate(operation) operation[0].state = state if state == operation[0].states['FINISHED']: operation[0].finish = self.get_current_timestamp() self.log.debug('Changing operation=%s state to %s' % (op_id, state)) if autonomous: operation[0].autonomous = 0 if operation[0].autonomous else 1 self.log.debug('Toggled operation=%s autonomous to %s' % (op_id, bool(operation[0].autonomous))) if obfuscator: operation[0].obfuscator = obfuscator self.log.debug('Updated operation=%s obfuscator to %s' % (op_id, operation[0].obfuscator))
Example #5
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def connections_retrieve(request: web.BaseRequest): """ Request handler for fetching a single connection record. Args: request: aiohttp request object Returns: The connection record response """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] try: record = await ConnectionRecord.retrieve_by_id(context, connection_id) result = record.serialize() except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except BaseModelError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response(result)
Example #6
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def connections_establish_inbound(request: web.BaseRequest): """ Request handler for setting the inbound connection on a connection record. Args: request: aiohttp request object """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] outbound_handler = request.app["outbound_message_router"] inbound_connection_id = request.match_info["ref_id"] try: connection = await ConnectionRecord.retrieve_by_id(context, connection_id) connection_mgr = ConnectionManager(context) await connection_mgr.establish_inbound( connection, inbound_connection_id, outbound_handler ) except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except (StorageError, WalletError, ConnectionManagerError) as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({})
Example #7
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def connections_remove(request: web.BaseRequest): """ Request handler for removing a connection record. Args: request: aiohttp request object """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] try: connection = await ConnectionRecord.retrieve_by_id(context, connection_id) await connection.delete_record(context) except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except StorageError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({})
Example #8
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def actionmenu_close(request: web.BaseRequest): """ Request handler for closing the menu associated with a connection. Args: request: aiohttp request object """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] menu = await retrieve_connection_menu(connection_id, context) if not menu: raise web.HTTPNotFound( reason=f"No {MENU_RECORD_TYPE} record found for connection {connection_id}" ) try: await save_connection_menu(None, connection_id, context) except StorageError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({})
Example #9
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def credential_exchange_publish_revocations(request: web.BaseRequest): """ Request handler for publishing pending revocations to the ledger. Args: request: aiohttp request object Returns: Credential revocation ids published as revoked by revocation registry id. """ context = request.app["request_context"] body = await request.json() rrid2crid = body.get("rrid2crid") credential_manager = CredentialManager(context) try: results = await credential_manager.publish_pending_revocations(rrid2crid) except (RevocationError, StorageError, IssuerError, LedgerError) as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({"rrid2crid": results})
Example #10
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def credential_exchange_remove(request: web.BaseRequest): """ Request handler for removing a credential exchange record. Args: request: aiohttp request object """ context = request.app["request_context"] outbound_handler = request.app["outbound_message_router"] credential_exchange_id = request.match_info["cred_ex_id"] cred_ex_record = None try: cred_ex_record = await V10CredentialExchange.retrieve_by_id( context, credential_exchange_id ) await cred_ex_record.delete_record(context) except StorageNotFoundError as err: await internal_error(err, web.HTTPNotFound, cred_ex_record, outbound_handler) except StorageError as err: await internal_error(err, web.HTTPBadRequest, cred_ex_record, outbound_handler) return web.json_response({})
Example #11
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def presentation_exchange_remove(request: web.BaseRequest): """ Request handler for removing a presentation exchange record. Args: request: aiohttp request object """ context = request.app["request_context"] presentation_exchange_id = request.match_info["pres_ex_id"] try: presentation_exchange_record = await V10PresentationExchange.retrieve_by_id( context, presentation_exchange_id ) await presentation_exchange_record.delete_record(context) except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except StorageError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({})
Example #12
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def wallet_get_public_did(request: web.BaseRequest): """ Request handler for fetching the current public DID. Args: request: aiohttp request object Returns: The DID info """ context = request.app["request_context"] wallet: BaseWallet = await context.inject(BaseWallet, required=False) if not wallet: raise web.HTTPForbidden(reason="No wallet available") try: info = await wallet.get_public_did() except WalletError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({"result": format_did_info(info)})
Example #13
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def presentation_exchange_retrieve(request: web.BaseRequest): """ Request handler for fetching a single presentation exchange record. Args: request: aiohttp request object Returns: The presentation exchange record response """ context = request.app["request_context"] presentation_exchange_id = request.match_info["pres_ex_id"] try: record = await V10PresentationExchange.retrieve_by_id( context, presentation_exchange_id ) result = record.serialize() except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except (BaseModelError, StorageError) as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response(result)
Example #14
Source File: docker-entrypoint.py From pydf with MIT License | 6 votes |
def generate(request): start = time() config = {} for k, v in request.headers.items(): if k.startswith('Pdf-') or k.startswith('Pdf_'): config[k[4:].lower()] = v.lower() data = await request.read() if not data: logger.info('Request with no body data') raise web.HTTPBadRequest(text='400: no HTML data to convert to PDF in request body\n') try: pdf_content = await app['apydf'].generate_pdf(data.decode(), **config) except RuntimeError as e: logger.info('Error generating PDF, time %0.2fs, config: %s', time() - start, config) return web.Response(text=str(e) + '\n', status=418) else: logger.info('PDF generated in %0.2fs, html-len %d, pdf-len %d', time() - start, len(data), len(pdf_content)) return web.Response(body=pdf_content, content_type='application/pdf')
Example #15
Source File: views.py From trace-examples with BSD 3-Clause "New" or "Revised" License | 6 votes |
def vote(request): async with request.app['db'].acquire() as conn: question_id = int(request.match_info['question_id']) data = await request.post() try: choice_id = int(data['choice']) except (KeyError, TypeError, ValueError) as e: raise web.HTTPBadRequest( text='You have not specified choice value') from e try: await db.vote(conn, question_id, choice_id) except db.RecordNotFound as e: raise web.HTTPNotFound(text=str(e)) router = request.app.router url = router['results'].url(parts={'question_id': question_id}) return web.HTTPFound(location=url)
Example #16
Source File: test_jwt_identity.py From aiohttp-security with Apache License 2.0 | 6 votes |
def test_identify_broken_scheme(loop, make_token, aiohttp_client): kwt_secret_key = 'Key' token = make_token({'login': 'Andrew'}, kwt_secret_key) async def check(request): policy = request.app[IDENTITY_KEY] try: await policy.identify(request) except ValueError as exc: raise web.HTTPBadRequest(reason=exc) return web.Response() app = web.Application() _setup(app, JWTIdentityPolicy(kwt_secret_key), Autz()) app.router.add_route('GET', '/', check) client = await aiohttp_client(app) headers = {'Authorization': 'Token {}'.format(token.decode('utf-8'))} resp = await client.get('/', headers=headers) assert 400 == resp.status assert 'Invalid authorization scheme' in resp.reason
Example #17
Source File: http_charfinder2.py From notebooks with MIT License | 6 votes |
def get_chars(request): peername = request.transport.get_extra_info('peername') print('Request from: {}, GET data: {!r}'.format(peername, dict(request.GET))) query = request.GET.get('query', '') if query: try: start = int(request.GET.get('start', 0)) stop = int(request.GET.get('stop', sys.maxsize)) except ValueError: raise web.HTTPBadRequest() stop = min(stop, start+RESULTS_PER_REQUEST) num_results, chars = index.find_chars(query, start, stop) else: raise web.HTTPBadRequest() text = ''.join(char if n % 64 else char+'\n' for n, char in enumerate(chars, 1)) response_data = {'total': num_results, 'start': start, 'stop': stop} print('Response to query: {query!r}, start: {start}, stop: {stop}'.format( query=query, **response_data)) response_data['chars'] = text json_obj = json.dumps(response_data) print('Sending {} characters'.format(len(text))) headers = {'Access-Control-Allow-Origin': '*'} return web.Response(content_type=TEXT_TYPE, headers=headers, text=json_obj)
Example #18
Source File: routes.py From dffml with MIT License | 6 votes |
def get_source_contexts(self, request, sctx_label_list): sources_context = SourcesContext([]) for label in sctx_label_list: sctx = request.app["source_contexts"].get(label, None) if sctx is None: raise web.HTTPNotFound( text=list(SOURCE_NOT_LOADED.values())[0], content_type="application/json", ) sources_context.append(sctx) if not sources_context: raise web.HTTPBadRequest( text=list(MODEL_NO_SOURCES.values())[0], content_type="application/json", ) return sources_context
Example #19
Source File: public.py From mautrix-facebook with GNU Affero General Public License v3.0 | 6 votes |
def check_token(self, request: web.Request) -> Optional['u.User']: try: token = request.headers["Authorization"] token = token[len("Bearer "):] except KeyError: raise web.HTTPBadRequest(body='{"error": "Missing Authorization header"}', headers=self._headers) except IndexError: raise web.HTTPBadRequest(body='{"error": "Malformed Authorization header"}', headers=self._headers) if self.shared_secret and token == self.shared_secret: try: user_id = request.query["user_id"] except KeyError: raise web.HTTPBadRequest(body='{"error": "Missing user_id query param"}', headers=self._headers) else: user_id = self.verify_token(token) if not user_id: raise web.HTTPForbidden(body='{"error": "Invalid token"}', headers=self._headers) user = u.User.get_by_mxid(user_id) return user
Example #20
Source File: utils.py From swagger-django-generator with BSD 3-Clause "New" or "Revised" License | 6 votes |
def body_to_dict(body, schema): # type: (str, Dict) -> Dict """ :param body: The body content :param schema: The expected JSONSchema :return: A dictionary containing the parsed body :raises SuspiciousOperation: If the body is not in JSON format, or does not conform to the specified schema. """ try: data = json.loads(body) jsonschema.validate(data, schema=schema) return data except Exception as e: # The SuspiciousOperation exception will result in an # HttpResponseBadRequest response. raise HTTPBadRequest()
Example #21
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def wallet_create_did(request: web.BaseRequest): """ Request handler for creating a new local DID in the wallet. Args: request: aiohttp request object Returns: The DID info """ context = request.app["request_context"] wallet: BaseWallet = await context.inject(BaseWallet, required=False) if not wallet: raise web.HTTPForbidden(reason="No wallet available") try: info = await wallet.create_local_did() except WalletError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({"result": format_did_info(info)})
Example #22
Source File: handlers.py From dp-agent with Apache License 2.0 | 5 votes |
def handle_api_request(self, request): response = {} register_msg = request.app['agent'].register_msg if request.method == 'POST': if 'content-type' not in request.headers \ or not request.headers['content-type'].startswith('application/json'): raise web.HTTPBadRequest(reason='Content-Type should be application/json') data = await request.json() user_id = data.pop('user_id') payload = data.pop('payload', '') deadline_timestamp = None if self.response_time_limit: deadline_timestamp = time() + self.response_time_limit if not user_id: raise web.HTTPBadRequest(reason='user_id key is required') command_performed = await handle_command(payload, user_id, request.app['agent'].state_manager) if command_performed: return web.json_response({}) response = await asyncio.shield( register_msg(utterance=payload, user_telegram_id=user_id, user_device_type=data.pop('user_device_type', 'http'), date_time=datetime.now(), location=data.pop('location', ''), channel_type='http_client', message_attrs=data, require_response=True, deadline_timestamp=deadline_timestamp) ) if response is None: raise RuntimeError('Got None instead of a bot response.') return web.json_response(self.output_formatter(response['dialog'].to_dict()))
Example #23
Source File: handlers.py From dp-agent with Apache License 2.0 | 5 votes |
def ws_handler(self, request): register_msg = request.app['agent'].register_msg ws = web.WebSocketResponse() await ws.prepare(request) while True: msg = await ws.receive() if msg.type == aiohttp.WSMsgType.text: data = msg.json() user_id = data.pop('user_id') payload = data.pop('payload', '') deadline_timestamp = None if not user_id: raise web.HTTPBadRequest(reason='user_id key is required') command_performed = await handle_command(payload, user_id, request.app['agent'].state_manager) if command_performed: await ws.send_json('command_performed') continue response = await register_msg( utterance=payload, user_telegram_id=user_id, user_device_type=data.pop('user_device_type', 'websocket'), date_time=datetime.now(), location=data.pop('location', ''), channel_type='ws_client', message_attrs=data, require_response=True, deadline_timestamp=deadline_timestamp ) if response is None: raise RuntimeError('Got None instead of a bot response.') await ws.send_json(self.output_formatter(response['dialog'].to_dict())) else: await ws.close() break return ws
Example #24
Source File: web_handler.py From mkctf with GNU General Public License v3.0 | 5 votes |
def check_challenge_flag(self, request): if not request.has_body: raise web.HTTPBadRequest(reason="JSON body is missing.") try: body = await request.json() except: raise web.HTTPBadRequest(reason="JSON body cannot be parsed.") flag = body.get('flag') if not flag: raise web.HTTPBadRequest(reason="JSON body does not contain 'flag' key as expected.") challenge = self._api.find(request.match_info['slug']) if challenge: valid = (challenge['conf'].get('flag') == flag) return web.json_response({'valid': valid})
Example #25
Source File: views.py From aiohttp_admin with Apache License 2.0 | 5 votes |
def vote(self, request): question_id = int(request.match_info['question_id']) data = await request.post() try: choice_id = int(data['choice']) except (KeyError, TypeError, ValueError) as e: raise web.HTTPBadRequest( text='You have not specified choice value') from e try: await db.vote(self.postgres, question_id, choice_id) except db.RecordNotFound as e: raise web.HTTPNotFound(text=str(e)) router = request.app.router url = router['results'].url(parts={'question_id': question_id}) return web.HTTPFound(location=url)
Example #26
Source File: public.py From mautrix-facebook with GNU Affero General Public License v3.0 | 5 votes |
def login(self, request: web.Request) -> web.Response: user = self.check_token(request) if not user.user_agent: user.user_agent = request.headers.get("User-Agent", None) try: data = await request.json() except json.JSONDecodeError: raise web.HTTPBadRequest(body='{"error": "Malformed JSON"}', headers=self._headers) try: session = await fbchat.Session.from_cookies(data, user_agent=user.user_agent) except fbchat.FacebookError: self.log.debug("Failed to log in", exc_info=True) raise web.HTTPUnauthorized(body='{"error": "Facebook authorization failed"}', headers=self._headers) if not await session.is_logged_in(): raise web.HTTPUnauthorized(body='{"error": "Facebook authorization failed"}', headers=self._headers) await user.on_logged_in(session) if user.command_status and user.command_status.get("action") == "Login": user.command_status = None return web.Response(body='{}', status=200, headers=self._headers)
Example #27
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 5 votes |
def wallet_rotate_did_keypair(request: web.BaseRequest): """ Request handler for rotating local DID keypair. Args: request: aiohttp request object Returns: An empty JSON response """ context = request.app["request_context"] wallet: BaseWallet = await context.inject(BaseWallet, required=False) if not wallet: raise web.HTTPForbidden(reason="No wallet available") did = request.query.get("did") if not did: raise web.HTTPBadRequest(reason="Request query must include DID") try: did_info = await wallet.get_local_did(did) if did_info.metadata.get("public", False): # call from ledger API instead to propagate through ledger NYM transaction raise web.HTTPBadRequest(reason=f"DID {did} is public") await wallet.rotate_did_keypair_start(did) # do not take seed over the wire await wallet.rotate_did_keypair_apply(did) except WalletNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except WalletError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({})
Example #28
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 5 votes |
def get_did_endpoint(request: web.BaseRequest): """ Request handler for getting a verkey for a DID from the ledger. Args: request: aiohttp request object """ context = request.app["request_context"] ledger = await context.inject(BaseLedger, required=False) if not ledger: reason = "No ledger available" if not context.settings.get_value("wallet.type"): reason += ": missing wallet-type?" raise web.HTTPForbidden(reason=reason) did = request.query.get("did") if not did: raise web.HTTPBadRequest(reason="Request query must include DID") async with ledger: try: r = await ledger.get_endpoint_for_did(did) except LedgerError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({"endpoint": r})
Example #29
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 5 votes |
def get_did_verkey(request: web.BaseRequest): """ Request handler for getting a verkey for a DID from the ledger. Args: request: aiohttp request object """ context = request.app["request_context"] ledger = await context.inject(BaseLedger, required=False) if not ledger: reason = "No ledger available" if not context.settings.get_value("wallet.type"): reason += ": missing wallet-type?" raise web.HTTPForbidden(reason=reason) did = request.query.get("did") if not did: raise web.HTTPBadRequest(reason="Request query must include DID") async with ledger: try: result = await ledger.get_key_for_did(did) if not result: raise web.HTTPNotFound(reason=f"DID {did} is not on the ledger") except LedgerError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({"verkey": result})
Example #30
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 5 votes |
def register_ledger_nym(request: web.BaseRequest): """ Request handler for registering a NYM with the ledger. Args: request: aiohttp request object """ context = request.app["request_context"] ledger = await context.inject(BaseLedger, required=False) if not ledger: reason = "No ledger available" if not context.settings.get_value("wallet.type"): reason += ": missing wallet-type?" raise web.HTTPForbidden(reason=reason) did = request.query.get("did") verkey = request.query.get("verkey") if not did or not verkey: raise web.HTTPBadRequest( reason="Request query must include both did and verkey" ) alias = request.query.get("alias") role = request.query.get("role") if role == "reset": # indy: empty to reset, null for regular user role = "" # visually: confusing - correct 'reset' to empty string here success = False async with ledger: try: await ledger.register_nym(did, verkey, alias, role) success = True except LedgerTransactionError as err: raise web.HTTPForbidden(reason=err.roll_up) return web.json_response({"success": success})