sysid / sse-starlette

BSD 3-Clause "New" or "Revised" License
504 stars 35 forks source link

returning a stream event without "data:" #63

Closed syberkitten closed 1 year ago

syberkitten commented 1 year ago

Hi

It seems like the "data:" prefix is always returned when a stream text fragment is returned to client.

In most cases this can be fixed on the client but it would be better to be able to specify if you really need this prefix or just return that raw data as it is.

code is in sse.py:

    if self.data is not None:
        for chunk in self.LINE_SEP_EXPR.split(str(self.data)):
            buffer.write(f"data: {chunk}")
            buffer.write(self._sep)

I can do a PR/MR if makes it easier, simplest is to add to the yield that is going to the ServerSentEvent:

for example: yield dict(data={ "text": "my text", }, data_prefix="")

syberkitten commented 1 year ago

class ServerSentEvent: def init( self, data: Optional[Any] = None, *, event: Optional[str] = None, id: Optional[int] = None, retry: Optional[int] = None, comment: Optional[str] = None, sep: Optional[str] = None, data_prefix="data: ", )

        if self.data is not None:
          for chunk in self.LINE_SEP_EXPR.split(str(self.data)):
              buffer.write(f"{self.data_prefix}{chunk}")
              buffer.write(self._sep)
paxcodes commented 1 year ago

Correct me if I'm wrong but it seems from the reading of the SSE spec (https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface), the "data: " prefix is required if you want to send data to be processed by clients. Otherwise, the line will/should be ignored by clients following the spec.   

18 Jun 2023, 02:21 by @.***:

Hi

It seems like the "data:" prefix is always returned when a stream text fragment is returned to client.

In most cases this can be fixed on the client but it would be better to be able to specify if you really need this prefix or just return that raw data as it is.

code is in sse.py:

if self.data is not None:        for chunk in self.LINE_SEP_EXPR.split(str(self.data)):            buffer.write(f"data: {chunk}")            buffer.write(self._sep)

I can do a PR/MR if makes it easier, simplest is to add to the yield that is going to the ServerSentEvent:

for example: yield dict(data={ "text": "my text", }, data_prefix="")

— Reply to this email directly, > view it on GitHub https://github.com/sysid/sse-starlette/issues/63> , or > unsubscribe https://github.com/notifications/unsubscribe-auth/ADIDWNVVMOWVR63KR2VWMFDXL3CBRANCNFSM6AAAAAAZKYUZ4Q> . You are receiving this because you are subscribed to this thread.> Message ID: > <sysid/sse-starlette/issues/63> @> github> .> com>

sysid commented 1 year ago

My understanding concurs with @paxcodes . Please correct my understanding by pointing to the respective spec or an authoritative example.

syberkitten commented 1 year ago

hi @sysid and @paxcodes thanks for pointing my attention to this, closing the merge request.