How to use the aiohttp.web.HTTPNotFound 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 mozilla / PollBot / tests / test_views.py View on Github external
async def error404(request):
        return web.HTTPNotFound()
github GNS3 / gns3-server / gns3server / controller / link.py View on Github external
async def add_node(self, node, adapter_number, port_number, label=None, dump=True):
        """
        Add a node to the link

        :param dump: Dump project on disk
        """

        port = node.get_port(adapter_number, port_number)
        if port is None:
            raise aiohttp.web.HTTPNotFound(text="Port {}/{} for {} not found".format(adapter_number, port_number, node.name))
        if port.link is not None:
            raise aiohttp.web.HTTPConflict(text="Port is already used")

        self._link_type = port.link_type

        for other_node in self._nodes:
            if other_node["node"] == node:
                raise aiohttp.web.HTTPConflict(text="Cannot connect to itself")

            if node.node_type in ["nat", "cloud"]:
                if other_node["node"].node_type in ["nat", "cloud"]:
                    raise aiohttp.web.HTTPConflict(text="Connecting a {} to a {} is not allowed".format(other_node["node"].node_type, node.node_type))

            # Check if user is not connecting serial => ethernet
            other_port = other_node["node"].get_port(other_node["adapter_number"], other_node["port_number"])
            if other_port is None:
github foglamp / FogLAMP / python / foglamp / services / core / api / notification.py View on Github external
async def post_notification(request):
    """
    Create a new notification to run a specific plugin

    :Example:
             curl -X POST http://localhost:8081/foglamp/notification -d '{"name": "Test Notification", "description":"Test Notification", "rule": "threshold", "channel": "email", "notification_type": "one shot", "enabled": false}'
             curl -X POST http://localhost:8081/foglamp/notification -d '{"name": "Test Notification", "description":"Test Notification", "rule": "threshold", "channel": "email", "notification_type": "one shot", "enabled": false, "rule_config": {}, "delivery_config": {}}'
    """
    try:
        notification_service = ServiceRegistry.get(s_type=ServiceRecord.Type.Notification.name)
        _address, _port = notification_service[0]._address, notification_service[0]._port
    except service_registry_exceptions.DoesNotExist:
        raise web.HTTPNotFound(reason="No Notification service available.")

    try:
        data = await request.json()
        if not isinstance(data, dict):
            raise ValueError('Data payload must be a valid JSON')

        name = data.get('name', None)
        description = data.get('description', None)
        rule = data.get('rule', None)
        channel = data.get('channel', None)
        notification_type = data.get('notification_type', None)
        enabled = data.get('enabled', None)
        rule_config = data.get('rule_config', {})
        delivery_config = data.get('delivery_config', {})

        if name is None or name.strip() == "":
github hail-is / hail / batch / batch / driver / main.py View on Github external
async def delete_batch(request):
    db = request.app['db']

    user = request.match_info['user']
    batch_id = int(request.match_info['batch_id'])

    record = db.select_and_fetchone(
        '''
SELECT state FROM batches WHERE user = %s AND id = %s;
''',
        (user, batch_id))
    if not record:
        raise web.HTTPNotFound()

    request.app['cancel_state_changed'].set()
    request.app['scheduler_state_changed'].set()

    return web.Response()
github hacs / integration / custom_components / hacs / frontend / views / static.py View on Github external
async def get(self, request, requested_file):  # pylint: disable=unused-argument
        """Serve static files."""
        servefile = "{}/custom_components/hacs/frontend/elements/{}".format(
            self.config_dir, requested_file
        )

        if os.path.exists(servefile + ".gz"):
            return web.FileResponse(servefile + ".gz")
        else:
            if os.path.exists(servefile):
                return web.FileResponse(servefile)
            else:
                raise HTTPNotFound
github fluentpython / example-code-2e / 20-futures / countries / flags2_asyncio.py View on Github external
def get_flag(base_url, cc): # <2>
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    resp = yield from aiohttp.request('GET', url)
    with contextlib.closing(resp):
        if resp.status == 200:
            image = yield from resp.read()
            return image
        elif resp.status == 404:
            raise web.HTTPNotFound()
        else:
            raise aiohttp.HttpProcessingError(
                code=resp.status, message=resp.reason,
                headers=resp.headers)
github foglamp / FogLAMP / python / foglamp / services / core / api / task.py View on Github external
plugin_config = plugin_info['config']
            script = '["tasks/north"]'
            process_name = 'north'
        except FileNotFoundError as ex:
            # Checking for C-type plugins
            script = '["tasks/north_c"]'
            plugin_info = apiutils.get_plugin_info(plugin, dir=task_type)
            if plugin_info['type'] != task_type:
                msg = "Plugin of {} type is not supported".format(plugin_info['type'])
                _logger.exception(msg)
                return web.HTTPBadRequest(reason=msg)
            plugin_config = plugin_info['config']
            process_name = 'north_c'
            if not plugin_config:
                _logger.exception("Plugin %s import problem from path %s. %s", plugin, plugin_module_path, str(ex))
                raise web.HTTPNotFound(reason='Plugin "{}" import problem from path "{}"'.format(plugin, plugin_module_path))
        except TypeError as ex:
            raise web.HTTPBadRequest(reason=str(ex))
        except Exception as ex:
            _logger.exception("Failed to fetch plugin configuration. %s", str(ex))
            raise web.HTTPInternalServerError(reason='Failed to fetch plugin configuration.')

        storage = connect.get_storage_async()
        config_mgr = ConfigurationManager(storage)

        # Abort the operation if there are already executed tasks
        payload = PayloadBuilder() \
            .SELECT(["id", "schedule_name"]) \
            .WHERE(['schedule_name', '=', name]) \
            .LIMIT(1) \
            .payload()
github Kenny2github / kenny2automate / kenny2automate / server / __init__.py View on Github external
def notfound(self, *_):
        raise web.HTTPNotFound(
            text=self.letext('404.html'),
            content_type='text/html'
        )
github GNS3 / gns3-server / gns3server / controller / project.py View on Github external
def get_node(self, node_id):
        """
        Return the node or raise a 404 if the node is unknown
        """
        try:
            return self._nodes[node_id]
        except KeyError:
            raise aiohttp.web.HTTPNotFound(text="Node ID {} doesn't exist".format(node_id))
github foglamp / FogLAMP / python / foglamp / services / core / api / backup_restore.py View on Github external
"""
    Restore from a backup
    :Example: curl -X PUT http://localhost:8081/foglamp/backup/1/restore
    """

    # TODO: FOGL-861
    backup_id = request.match_info.get('backup_id', None)
    try:
        backup_id = int(backup_id)
        restore = Restore(connect.get_storage_async())
        status = await 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))