How to use the aiohttp.web.HTTPBadRequest function in aiohttp

To help you get started, we’ve selected a few aiohttp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aio-libs / aiohttp / tests / autobahn / server.py View on Github external
async def wshandler(request):
    ws = web.WebSocketResponse(autoclose=False)
    is_ws = ws.can_prepare(request)
    if not is_ws:
        return web.HTTPBadRequest()

    await ws.prepare(request)

    while True:
        msg = await ws.receive()

        if msg.type == web.WSMsgType.TEXT:
            await ws.send_str(msg.data)
        elif msg.type == web.WSMsgType.BINARY:
            await ws.send_bytes(msg.data)
        elif msg.type == web.WSMsgType.CLOSE:
            await ws.close()
            break
        else:
            break
github GNS3 / gns3-server / gns3server / controller / template_manager.py View on Github external
:param settings: template settings

        :returns: Template object
        """

        template_id = settings.get("template_id", "")
        if template_id in self._templates:
            raise aiohttp.web.HTTPConflict(text="Template ID '{}' already exists".format(template_id))
        else:
            template_id = settings.setdefault("template_id", str(uuid.uuid4()))
        try:
            template = Template(template_id, settings)
        except jsonschema.ValidationError as e:
            message = "JSON schema error adding template with JSON data '{}': {}".format(settings, e.message)
            raise aiohttp.web.HTTPBadRequest(text=message)

        from . import Controller
        Controller.instance().check_can_write_config()
        self._templates[template.id] = template
        Controller.instance().save()
        Controller.instance().notification.controller_emit("template.created", template.__json__())
        return template
github Kruptein / PlanarAlly / server / api / http / auth.py View on Github external
async def register(request):
    username = await authorized_userid(request)
    if username:
        return web.HTTPOk()

    data = await request.json()
    username = data["username"]
    password = data["password"]
    if User.by_name(username):
        return web.HTTPConflict(reason="Username already taken")
    elif not username:
        return web.HTTPBadRequest(reason="Please provide a username")
    elif not password:
        return web.HTTPBadRequest(reason="Please provide a password")
    else:
        with db.atomic():
            u = User(name=username)
            u.set_password(password)
            u.save()
        response = web.HTTPOk()
        await remember(request, response, username)
        return response
github hyperledger / aries-cloudagent-python / aries_cloudagent / protocols / present_proof / v1_0 / routes.py View on Github external
"""
    r_time = get_timer()

    context = request.app["request_context"]
    outbound_handler = request.app["outbound_message_router"]

    body = await request.json()

    connection_id = body.get("connection_id")
    try:
        connection_record = await ConnectionRecord.retrieve_by_id(
            context, connection_id
        )
    except StorageNotFoundError as err:
        raise web.HTTPBadRequest(reason=err.roll_up) from err

    if not connection_record.is_ready:
        raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready")

    comment = body.get("comment")
    indy_proof_request = body.get("proof_request")
    if not indy_proof_request.get("nonce"):
        indy_proof_request["nonce"] = await generate_pr_nonce()

    presentation_request_message = PresentationRequest(
        comment=comment,
        request_presentations_attach=[
            AttachDecorator.from_indy_dict(
                indy_dict=indy_proof_request,
                ident=ATTACH_DECO_IDS[PRESENTATION_REQUEST],
            )
github qqj1228 / Python_Blog / www / webframe.py View on Github external
async def __call__(self, request):
        kw = None
        if self._has_var_kw_arg or self._has_named_kw_arg or self._required_kw_args:
            if request.method == 'POST':
                if not request.content_type:
                    return web.HTTPBadRequest('Missing Content-Type.')
                ct = request.content_type.lower()
                if ct.startswith('application/json'):
                    params = await request.json()
                    if not isinstance(params, dict):
                        return web.HTTPBadRequest('JSON body must be object.')
                    kw = params
                elif ct.startswith('application/x-www-form-urlencoded') or \
                        ct.startswith('multipart/form-data'):
                    params = await request.post()
                    kw = dict(**params)
                else:
                    return web.HTTPBadRequest('Unsupported Content-Type: %s' % request.content_type)
            if request.method == 'GET':
                qs = request.query_string
                if qs:
                    kw = dict()
                    for k, v in parse.parse_qs(qs, True).items():
                        kw[k] = v[0]
        if kw is None:
            kw = dict(**request.match_info)
        else:
github Trim21 / bgm-tv-auto-tracker / server / views / __init__.py View on Github external
async def get(self):
        request = self.request
        try:
            ep_id = int(request.query.get('bgm_ep_id'))
        except (ValueError, TypeError):
            return web.HTTPBadRequest()
        data = await request.app.db.get_collection(
            mongo_collection_name.FINAL_BGM_EP_MAP
        ).find({'bgm_ep_id': ep_id}, {'_id': 0}).to_list(None)
        return web.json_response({'status': 'success', 'data': data})
github Terrance / IMMP / immp / hook / webui / __init__.py View on Github external
async def group_add(self, request):
        post = await request.post()
        try:
            name = post["name"]
        except KeyError:
            raise web.HTTPBadRequest
        if not name:
            raise web.HTTPBadRequest
        if name in self.host:
            raise web.HTTPConflict
        self.host.add_group(immp.Group(name, {}, self.host))
        raise web.HTTPFound(self.ctx.url_for("group", name=name))
github roll / interest-py / interest / backend.py View on Github external
NotModified = web.HTTPNotModified
    """304 Not Modified.
    """
    UseProxy = web.HTTPUseProxy
    """305 Use Proxy.
    """
    TemporaryRedirect = web.HTTPTemporaryRedirect
    """307 Temporary Redirect.
    """
    Error = web.HTTPError
    """4/5xx Client or Server Error.
    """
    ClientError = web.HTTPClientError
    """4xx Client Error.
    """
    BadRequest = web.HTTPBadRequest
    """400 Bad Request.
    """
    Unauthorized = web.HTTPUnauthorized
    """401 Unauthorized.
    """
    PaymentRequired = web.HTTPPaymentRequired
    """402 Payment Required.
    """
    Forbidden = web.HTTPForbidden
    """403 Forbidden.
    """
    NotFound = web.HTTPNotFound
    """404 Not Found.
    """
    MethodNotAllowed = web.HTTPMethodNotAllowed
    """405 Method Not Allowed.
github PetterS / realtimechess / auth.py View on Github external
async def anonymous_login_handler(request):
	data = await request.post()
	logging.info("LOGIN %s", data)
	name = data.get('name', None)
	if name is None:
		raise aiohttp.web.HTTPBadRequest(text="Need name.")
	destination = data.get("destination", None)
	if destination is None:
		destination = "/"

	# Require A-Z for now.
	if len(name) > 20 or re.match(r"^[\sa-zA-Z0-9_-]+$", name) is None:
		raise aiohttp.web.HTTPBadRequest(text="Invalid name.")

	manager = request.app["user_manager"]
	password = manager.login(name)
	logging.info("Anonymous user: %s.", name)

	response = aiohttp.web.HTTPFound(destination)
	response.set_cookie('name', name, max_age=LONG_TIME_IN_SECONDS, path='/')
	response.set_cookie(
	    'password', password, max_age=LONG_TIME_IN_SECONDS, path='/')
	raise response
github GNS3 / gns3-server / gns3server / modules / base_manager.py View on Github external
def get_vm(self, uuid):
        """
        Returns a VM instance.

        :param uuid: VM UUID

        :returns: VM instance
        """

        try:
            UUID(uuid, version=4)
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(text="{} is not a valid UUID".format(uuid))

        if uuid not in self._vms:
            raise aiohttp.web.HTTPNotFound(text="UUID {} doesn't exist".format(uuid))
        return self._vms[uuid]