How to use the h2.events.DataReceived function in h2

To help you get started, we’ve selected a few h2 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 web-platform-tests / wpt / tools / wptserve / wptserve / server.py View on Github external
stream_handler = H2HandlerCopy(self, frame, rfile)

                stream_handler.server.rewriter.rewrite(stream_handler)
                request = H2Request(stream_handler)
                response = H2Response(stream_handler, request)

                req_handler = stream_handler.server.router.get_handler(request)

                if hasattr(req_handler, "frame_handler"):
                    # Convert this to a handler that will utilise H2 specific functionality, such as handling individual frames
                    req_handler = self.frame_handler(request, response, req_handler)

                if hasattr(req_handler, 'handle_headers'):
                    req_handler.handle_headers(frame, request, response)

            elif isinstance(frame, DataReceived):
                wfile.write(frame.data)

                if hasattr(req_handler, 'handle_data'):
                    req_handler.handle_data(frame, request, response)

                if frame.stream_ended:
                    wfile.close()
            elif frame is None or isinstance(frame, (StreamReset, StreamEnded, ConnectionTerminated)):
                self.logger.debug('(%s - %s) Stream Reset, Thread Closing' % (self.uid, stream_id))
                break

            if request is not None:
                request.frames.append(frame)

            if hasattr(frame, "stream_ended") and frame.stream_ended:
                self.finish_handling(request, response, req_handler)
github grpc / grpc / test / http2_test / http2_base_server.py View on Github external
def dataReceived(self, data):
    try:
      events = self._conn.receive_data(data)
    except h2.exceptions.ProtocolError:
      # this try/except block catches exceptions due to race between sending
      # GOAWAY and processing a response in flight.
      return
    if self._conn.data_to_send:
      self.transport.write(self._conn.data_to_send())
    for event in events:
      if isinstance(event, h2.events.RequestReceived) and self._handlers.has_key('RequestReceived'):
        logging.info('RequestReceived Event for stream: %d' % event.stream_id)
        self._handlers['RequestReceived'](event)
      elif isinstance(event, h2.events.DataReceived) and self._handlers.has_key('DataReceived'):
        logging.info('DataReceived Event for stream: %d' % event.stream_id)
        self._handlers['DataReceived'](event)
      elif isinstance(event, h2.events.WindowUpdated) and self._handlers.has_key('WindowUpdated'):
        logging.info('WindowUpdated Event for stream: %d' % event.stream_id)
        self._handlers['WindowUpdated'](event)
      elif isinstance(event, h2.events.PingAcknowledged) and self._handlers.has_key('PingAcknowledged'):
        logging.info('PingAcknowledged Event')
        self._handlers['PingAcknowledged'](event)
    self.transport.write(self._conn.data_to_send())
github Kitware / VTK / ThirdParty / Twisted / vtkTwisted / src / twisted / web / _http2.py View on Github external
self.resetTimeout()

        try:
            events = self.conn.receive_data(data)
        except h2.exceptions.ProtocolError:
            # A remote protocol error terminates the connection.
            dataToSend = self.conn.data_to_send()
            self.transport.write(dataToSend)
            self.transport.loseConnection()
            self.connectionLost("Protocol error from peer.")
            return

        for event in events:
            if isinstance(event, h2.events.RequestReceived):
                self._requestReceived(event)
            elif isinstance(event, h2.events.DataReceived):
                self._requestDataReceived(event)
            elif isinstance(event, h2.events.StreamEnded):
                self._requestEnded(event)
            elif isinstance(event, h2.events.StreamReset):
                self._requestAborted(event)
            elif isinstance(event, h2.events.WindowUpdated):
                self._handleWindowUpdate(event)
            elif isinstance(event, h2.events.PriorityUpdated):
                self._handlePriorityUpdate(event)
            elif isinstance(event, h2.events.ConnectionTerminated):
                self.transport.loseConnection()
                self.connectionLost("Shutdown by remote peer")

        dataToSend = self.conn.data_to_send()
        if dataToSend:
            self.transport.write(dataToSend)
github encode / uvicorn / uvicorn / protocols / http / h2_impl.py View on Github external
def handle_events(self, events: List[Event]) -> None:
        """ Handle recieved events """
        from pprint import pprint
        print("\n\n\n!!!!!!!!!!!")
        pprint(events)
        print("\n\n\n!!!!!!!!!!!")
        # import pdb; pdb.set_trace()
        for event in events:
            if isinstance(event, RemoteSettingsChanged):
                self.handle_remote_settings_changed(event)
            elif isinstance(event, RequestReceived):
                self.handle_request_received(event)
            elif isinstance(event, DataReceived):
                self.handle_data_received(event)
            elif isinstance(event, StreamEnded):
                self.handle_stream_ended(event)
            elif isinstance(event, SettingsAcknowledged):
                # TODO check if we can do anything else
                pass
            elif isinstance(event, StreamReset):
                raise NotImplementedError()
            elif isinstance(event, WindowUpdated):
                raise NotImplementedError()
            elif isinstance(event, PriorityUpdated):
                raise NotImplementedError()
            elif isinstance(event, ConnectionTerminated):
                self.transport.close()
                # raise NotImplementedError()
            else:
github python-hyper / hyper-h2 / examples / twisted / head_request.py View on Github external
def dataReceived(self, data):
        if not self.known_proto:
            self.known_proto = self.transport.negotiatedProtocol
            assert self.known_proto == b'h2'

        events = self.conn.receive_data(data)

        for event in events:
            if isinstance(event, ResponseReceived):
                self.handleResponse(event.headers, event.stream_id)
            elif isinstance(event, DataReceived):
                self.handleData(event.data, event.stream_id)
            elif isinstance(event, StreamEnded):
                self.endStream(event.stream_id)
            elif isinstance(event, SettingsAcknowledged):
                self.settingsAcked(event)
            elif isinstance(event, StreamReset):
                reactor.stop()
                raise RuntimeError("Stream reset: %d" % event.error_code)
            else:
                print(event)

        data = self.conn.data_to_send()
        if data:
            self.transport.write(data)
github python-hyper / hyper / hyper / http20 / connection.py View on Github external
# I/O occurs while the lock is held; waiting threads will see a delay.
        with self._lock:
            if self._sock is None:
                raise ConnectionError('tried to read after connection close')
            self._sock.fill()
            data = self._sock.buffer.tobytes()
            self._sock.advance_buffer(len(data))
            with self._conn as conn:
                events = conn.receive_data(data)
            stream_ids = set(getattr(e, 'stream_id', -1) for e in events)
            stream_ids.discard(-1)  # sentinel
            stream_ids.discard(0)  # connection events
            self.recent_recv_streams |= stream_ids

        for event in events:
            if isinstance(event, h2.events.DataReceived):
                self._adjust_receive_window(event.flow_controlled_length)
                self.streams[event.stream_id].receive_data(event)
            elif isinstance(event, h2.events.PushedStreamReceived):
                if self._enable_push:
                    self._new_stream(event.pushed_stream_id, local_closed=True)
                    self.streams[event.parent_stream_id].receive_push(event)
                else:
                    # Servers are forbidden from sending push promises when
                    # the ENABLE_PUSH setting is 0, but the spec leaves the
                    # client action undefined when they do it anyway. So we
                    # just refuse the stream and go about our business.
                    self._send_rst_frame(event.pushed_stream_id, 7)
            elif isinstance(event, h2.events.ResponseReceived):
                self.streams[event.stream_id].receive_response(event)
            elif isinstance(event, h2.events.TrailersReceived):
                self.streams[event.stream_id].receive_trailers(event)
github vmagamedov / grpclib / grpclib / protocol.py View on Github external
def __init__(
        self,
        handler: AbstractHandler,
        connection: Connection,
    ) -> None:
        self.handler = handler
        self.connection = connection

        self.processors = {
            RequestReceived: self.process_request_received,
            ResponseReceived: self.process_response_received,
            RemoteSettingsChanged: self.process_remote_settings_changed,
            SettingsAcknowledged: self.process_settings_acknowledged,
            DataReceived: self.process_data_received,
            WindowUpdated: self.process_window_updated,
            TrailersReceived: self.process_trailers_received,
            StreamEnded: self.process_stream_ended,
            StreamReset: self.process_stream_reset,
            PriorityUpdated: self.process_priority_updated,
            ConnectionTerminated: self.process_connection_terminated,
            PingReceived: self.process_ping_received,
            PingAckReceived: self.process_ping_ack_received,
            PingAcknowledged: self.process_ping_ack_received,  # deprecated
        }

        self.streams: _Streams = {}
github standy66 / purerpc / src / purerpc / grpclib / connection.py View on Github external
def receive_data(self, data: bytes):
        events = self.h2_connection.receive_data(data)
        grpc_events = []
        for event in events:
            if isinstance(event, h2.events.RequestReceived):
                grpc_events.extend(self._request_received(event))
            elif isinstance(event, h2.events.ResponseReceived):
                grpc_events.extend(self._response_received(event))
            elif isinstance(event, h2.events.TrailersReceived):
                grpc_events.extend(self._trailers_received(event))
            elif isinstance(event, h2.events.InformationalResponseReceived):
                grpc_events.extend(self._informational_response_received(event))
            elif isinstance(event, h2.events.DataReceived):
                grpc_events.extend(self._data_received(event))
            elif isinstance(event, h2.events.WindowUpdated):
                grpc_events.extend(self._window_updated(event))
            elif isinstance(event, h2.events.RemoteSettingsChanged):
                grpc_events.extend(self._remote_settings_changed(event))
            elif isinstance(event, h2.events.PingAcknowledged):
                grpc_events.extend(self._ping_acknowledged(event))
            elif isinstance(event, h2.events.StreamEnded):
                grpc_events.extend(self._stream_ended(event))
            elif isinstance(event, h2.events.StreamReset):
                grpc_events.extend(self._stream_reset(event))
            elif isinstance(event, h2.events.PushedStreamReceived):
                grpc_events.extend(self._push_stream_received(event))
            elif isinstance(event, h2.events.SettingsAcknowledged):
                grpc_events.extend(self._settings_acknowledged(event))
            elif isinstance(event, h2.events.PriorityUpdated):
github python-hyper / hyper-h2 / examples / eventlet / eventlet-server.py View on Github external
def run_forever(self):
        self.conn.initiate_connection()
        self.sock.sendall(self.conn.data_to_send())

        while True:
            data = self.sock.recv(65535)
            if not data:
                break

            events = self.conn.receive_data(data)

            for event in events:
                if isinstance(event, RequestReceived):
                    self.request_received(event.headers, event.stream_id)
                elif isinstance(event, DataReceived):
                    self.conn.reset_stream(event.stream_id)

            self.sock.sendall(self.conn.data_to_send())
github mike820324 / microProxy / microproxy / protocol / http2.py View on Github external
def handle_events(self, events):
        for event in events:
            logger.debug("event received from {0}: {1}".format(self.conn_type, event))
            if isinstance(event, ResponseReceived):
                self.handle_response(event)
            elif isinstance(event, RequestReceived):
                self.handle_request(event)
            elif isinstance(event, DataReceived):
                self.handle_data(event)
            elif isinstance(event, StreamEnded):
                self.handle_end_stream(event.stream_id)
            elif isinstance(event, StreamReset):
                self.handle_reset(event)
            elif isinstance(event, RemoteSettingsChanged):
                self.handle_update_settings(event)
            elif isinstance(event, WindowUpdated):
                self.handle_window_updates(event)
            elif isinstance(event, PushedStreamReceived):
                self.handle_pushed_stream(event)
            elif isinstance(event, PriorityUpdated):
                self.handle_priority_updates(event)
            elif isinstance(event, ConnectionTerminated):
                self.on_terminate(
                    event.additional_data, event.error_code,