예제 #1
0
    async def handler(self, request):
        """Main handler function for aiohttp."""
        request._view_error = False
        await notify(BeforeRenderViewEvent(request, self.view))
        request.record("viewrender")
        if app_settings["check_writable_request"](request):
            try:
                # We try to avoid collisions on the same instance of
                # guillotina
                view_result = await self.view()
                await commit(warn=False)
            except (ConflictError, TIDConflictError):
                await abort()
                # bubble this error up
                raise
            except (response.Response,
                    aiohttp.web_exceptions.HTTPException) as exc:
                await abort()
                view_result = exc
                request._view_error = True
            except Exception as e:
                await abort()
                view_result = generate_error_response(e, request,
                                                      "ServiceError")
                request._view_error = True
        else:
            try:
                view_result = await self.view()
            except (response.Response,
                    aiohttp.web_exceptions.HTTPException) as exc:
                view_result = exc
                request._view_error = True
            except Exception as e:
                request._view_error = True
                view_result = generate_error_response(e, request, "ViewError")
            finally:
                await abort()
        request.record("viewrendered")

        if IAioHTTPResponse.providedBy(view_result):
            resp = view_result
        else:
            resp = await apply_rendering(self.view, self.request, view_result)
            request.record("renderer")
            resp = await _apply_cors(request, resp)

        if not request._view_error:
            request.execute_futures()
        else:
            request.execute_futures("failure")

        self.debug(request, resp)

        request.record("finish")

        _clean_request(request, resp)
        del self.view
        del self.resource
        request.clear_futures()
        return resp
예제 #2
0
파일: ws.py 프로젝트: jordic/guillotina
    async def handle_ws_request(self, ws, message):
        method = app_settings['http_methods']['GET']
        path = tuple(p for p in message['value'].split('/') if p)

        from guillotina.traversal import traverse
        obj, tail = await traverse(self.request, self.request.container, path)

        if tail and len(tail) > 0:
            # convert match lookups
            view_name = routes.path_to_view_name(tail)
        elif not tail:
            view_name = ''
        else:
            raise

        permission = get_utility(IPermission, name='guillotina.AccessContent')

        security = get_adapter(self.request, IInteraction)
        allowed = security.check_permission(permission.id, obj)
        if not allowed:
            return ws.send_str(ujson.dumps({'error': 'Not allowed'}))

        try:
            view = query_multi_adapter((obj, self.request),
                                       method,
                                       name=view_name)
        except AttributeError:
            view = None

        try:
            view.__route__.matches(self.request, tail or [])
        except (KeyError, IndexError):
            view = None

        if view is None:
            return ws.send_str(ujson.dumps({'error': 'Not found'}))

        ViewClass = view.__class__
        view_permission = get_view_permission(ViewClass)
        if not security.check_permission(view_permission, view):
            return ws.send_str(ujson.dumps({'error': 'No view access'}))

        if hasattr(view, 'prepare'):
            view = (await view.prepare()) or view

        view_result = await view()
        if IAioHTTPResponse.providedBy(view_result):
            raise Exception('Do not accept raw aiohttp exceptions in ws')
        else:
            from guillotina.traversal import apply_rendering
            resp = await apply_rendering(view, self.request, view_result)

        # Return the value, body is always encoded
        ws.send_str(resp.body.decode('utf-8'))

        # Wait for possible value
        self.request.execute_futures()
예제 #3
0
 async def handler(self, request):
     """Main handler function for aiohttp."""
     request.record('finish')
     self.debug(request, self.resp)
     if IAioHTTPResponse.providedBy(self.resp):
         return self.resp
     else:
         return await apply_rendering(
             View(None, request), request, self.resp)
예제 #4
0
    async def handler(self, request):
        """Main handler function for aiohttp."""
        request._view_error = False
        request.record('viewrender')
        if app_settings['check_writable_request'](request):
            try:
                # We try to avoid collisions on the same instance of
                # guillotina
                view_result = await self.view()
                await commit(request, warn=False)
            except (ConflictError, TIDConflictError) as e:
                # bubble this error up
                raise
            except (response.Response,
                    aiohttp.web_exceptions.HTTPException) as exc:
                await abort(request)
                view_result = exc
                request._view_error = True
            except Exception as e:
                await abort(request)
                view_result = generate_error_response(e, request,
                                                      'ServiceError')
                request._view_error = True
        else:
            try:
                view_result = await self.view()
            except (response.Response,
                    aiohttp.web_exceptions.HTTPException) as exc:
                view_result = exc
                request._view_error = True
            except Exception as e:
                request._view_error = True
                view_result = generate_error_response(e, request, 'ViewError')
            finally:
                await abort(request)
        request.record('viewrendered')

        if IAioHTTPResponse.providedBy(view_result):
            resp = view_result
        else:
            resp = await apply_rendering(self.view, self.request, view_result)
            request.record('renderer')
            resp = await _apply_cors(request, resp)

        if not request._view_error:
            request.execute_futures()
        else:
            request.execute_futures('failure')

        self.debug(request, resp)

        request.record('finish')

        request.clear_futures()
        return resp
예제 #5
0
 async def handler(self, request):
     """Main handler function for aiohttp."""
     request.record('finish')
     self.debug(request, self.resp)
     if IAioHTTPResponse.providedBy(self.resp):
         return self.resp
     else:
         resp = await apply_rendering(
             View(None, request), request, self.resp)
         resp = await _apply_cors(request, resp)
         return resp
예제 #6
0
    async def handler(self, request):
        """Main handler function for aiohttp."""
        request._view_error = False
        await notify(BeforeRenderViewEvent(request, self.view))
        request.record('viewrender')
        if app_settings['check_writable_request'](request):
            try:
                # We try to avoid collisions on the same instance of
                # guillotina
                view_result = await self.view()
                await commit(request, warn=False)
            except (ConflictError, TIDConflictError):
                # bubble this error up
                raise
            except (response.Response, aiohttp.web_exceptions.HTTPException) as exc:
                await abort(request)
                view_result = exc
                request._view_error = True
            except Exception as e:
                await abort(request)
                view_result = generate_error_response(
                    e, request, 'ServiceError')
                request._view_error = True
        else:
            try:
                view_result = await self.view()
            except (response.Response, aiohttp.web_exceptions.HTTPException) as exc:
                view_result = exc
                request._view_error = True
            except Exception as e:
                request._view_error = True
                view_result = generate_error_response(e, request, 'ViewError')
            finally:
                await abort(request)
        request.record('viewrendered')

        if IAioHTTPResponse.providedBy(view_result):
            resp = view_result
        else:
            resp = await apply_rendering(self.view, self.request, view_result)
            request.record('renderer')
            resp = await _apply_cors(request, resp)

        if not request._view_error:
            request.execute_futures()
        else:
            request.execute_futures('failure')

        self.debug(request, resp)

        request.record('finish')

        request.clear_futures()
        return resp
예제 #7
0
    async def handler(self, request):
        """Main handler function for aiohttp."""
        request._view_error = False
        request.record('viewrender')
        if app_settings['check_writable_request'](request):
            try:
                # We try to avoid collisions on the same instance of
                # guillotina
                view_result = await self.view()
                await commit(request, warn=False)
            except (ConflictError, TIDConflictError) as e:
                # bubble this error up
                raise
            except (response.Response, aiohttp.web_exceptions.HTTPException) as exc:
                await abort(request)
                view_result = exc
                request._view_error = True
            except Exception as e:
                await abort(request)
                view_result = generate_error_response(
                    e, request, 'ServiceError')
                request._view_error = True
        else:
            try:
                view_result = await self.view()
            except (response.Response, aiohttp.web_exceptions.HTTPException) as exc:
                view_result = exc
                request._view_error = True
            except Exception as e:
                request._view_error = True
                view_result = generate_error_response(e, request, 'ViewError')
            finally:
                await abort(request)
        request.record('viewrendered')

        if IAioHTTPResponse.providedBy(view_result):
            resp = view_result
        else:
            resp = await apply_rendering(self.view, self.request, view_result)
            request.record('renderer')

            # Apply cors if its needed
            cors_renderer = app_settings['cors_renderer'](request)
            try:
                cors_headers = await cors_renderer.get_headers()
                cors_headers.update(resp.headers)
                resp._headers = cors_headers
                retry_attempts = getattr(request, '_retry_attempt', 0)
                if retry_attempts > 0:
                    resp.headers['X-Retry-Transaction-Count'] = str(retry_attempts)
            except response.Response as exc:
                resp = exc
            request.record('headers')

        if not request._view_error:
            request.execute_futures()
        else:
            request.execute_futures('failure')

        self.debug(request, resp)

        request.record('finish')

        request.clear_futures()
        return resp
예제 #8
0
    async def handle_ws_request(self, ws, message):
        method = app_settings["http_methods"]["GET"]
        try:
            frame_id = message["id"]
        except KeyError:
            frame_id = "0"

        parsed = parse.urlparse(message.get("path", message.get("value")))
        path = tuple(p for p in parsed.path.split("/") if p)

        from guillotina.traversal import traverse

        obj, tail = await traverse(self.request, task_vars.container.get(), path)

        if tail and len(tail) > 0:
            # convert match lookups
            view_name = routes.path_to_view_name(tail)
        elif not tail:
            view_name = ""
        else:
            raise

        permission = get_utility(IPermission, name="guillotina.AccessContent")

        security = get_security_policy()
        allowed = security.check_permission(permission.id, obj)
        if not allowed:
            return await ws.send_str(ujson.dumps({"error": "Not allowed"}))

        try:
            view = query_multi_adapter((obj, self.request), method, name=view_name)
        except AttributeError:
            view = None

        try:
            view.__route__.matches(self.request, tail or [])
        except (KeyError, IndexError):
            view = None

        if view is None:
            return await ws.send_str(ujson.dumps({"error": "Not found", "id": frame_id}))

        ViewClass = view.__class__
        view_permission = get_view_permission(ViewClass)
        if not security.check_permission(view_permission, view):
            return await ws.send_str(ujson.dumps({"error": "No view access", "id": frame_id}))

        if hasattr(view, "prepare"):
            view = (await view.prepare()) or view

        view_result = await view()
        if IAioHTTPResponse.providedBy(view_result):
            raise Exception("Do not accept raw aiohttp exceptions in ws")
        else:
            from guillotina.traversal import apply_rendering

            resp = await apply_rendering(view, self.request, view_result)

        # Return the value, body is always encoded
        response_object = ujson.dumps({"data": resp.body.decode("utf-8"), "id": frame_id})
        await ws.send_str(response_object)

        # Wait for possible value
        self.request.execute_futures()
예제 #9
0
    async def handle_ws_request(self, ws, message):
        method = app_settings['http_methods']['GET']
        try:
            frame_id = message['id']
        except KeyError:
            frame_id = '0'

        parsed = parse.urlparse(message.get('path', message.get('value')))
        path = tuple(p for p in parsed.path.split('/') if p)

        from guillotina.traversal import traverse
        obj, tail = await traverse(self.request, self.request.container, path)

        if tail and len(tail) > 0:
            # convert match lookups
            view_name = routes.path_to_view_name(tail)
        elif not tail:
            view_name = ''
        else:
            raise

        permission = get_utility(
            IPermission, name='guillotina.AccessContent')

        security = get_adapter(self.request, IInteraction)
        allowed = security.check_permission(permission.id, obj)
        if not allowed:
            return await ws.send_str(ujson.dumps({
                'error': 'Not allowed'
            }))

        try:
            view = query_multi_adapter(
                (obj, self.request), method, name=view_name)
        except AttributeError:
            view = None

        try:
            view.__route__.matches(self.request, tail or [])
        except (KeyError, IndexError):
            view = None

        if view is None:
            return await ws.send_str(ujson.dumps({
                'error': 'Not found',
                'id': frame_id
            }))

        ViewClass = view.__class__
        view_permission = get_view_permission(ViewClass)
        if not security.check_permission(view_permission, view):
            return await ws.send_str(ujson.dumps({
                'error': 'No view access',
                'id': frame_id
            }))

        if hasattr(view, 'prepare'):
            view = (await view.prepare()) or view

        view_result = await view()
        if IAioHTTPResponse.providedBy(view_result):
            raise Exception('Do not accept raw aiohttp exceptions in ws')
        else:
            from guillotina.traversal import apply_rendering
            resp = await apply_rendering(view, self.request, view_result)

        # Return the value, body is always encoded
        response_object = ujson.dumps({
            'data': resp.body.decode('utf-8'),
            'id': frame_id
        })
        await ws.send_str(response_object)

        # Wait for possible value
        self.request.execute_futures()