@@ -29,16 +29,41 @@ def __init__(self, ID: Optional[str] = None,
2929 data : Optional [str ] = None ,
3030 comment : Optional [str ] = None ,
3131 retry : Optional [int ] = None ) -> None :
32- if any ([ID , event , data , comment , retry ]):
32+ """构造sse消息.
33+
34+ 除了retry外至少要有1个参数.
35+
36+ Args:
37+ ID (Optional[str], optional): 消息id. Defaults to None.
38+ event (Optional[str], optional): 消息事件. Defaults to None.
39+ data (Optional[str], optional): 消息数据. Defaults to None.
40+ comment (Optional[str], optional): 消息注释. Defaults to None.
41+ retry (Optional[int], optional): 重连间隔时间,单位ms. Defaults to None.
42+
43+ Raises:
44+ TypeError: [description]
45+ ValueError: [description]
46+ """
47+ if any ([ID , event , data , comment ]):
3348 self .ID = ID
3449 self .event = event
3550 self .data = data
3651 self .retry = retry
3752 self .comment = comment
53+ if self .retry and not isinstance (self .retry , int ):
54+ raise TypeError ("retry argument must be int" )
3855 else :
39- raise ValueError ("at least one args" )
56+ raise ValueError ("at least one argument" )
57+
58+ def render (self , * , with_encode : bool = False ) -> Union [str , bytes ]:
59+ """渲染sse消息对象
4060
41- def render (self , with_encode : bool = False ) -> Union [str , bytes ]:
61+ Args:
62+ with_encode (bool, optional): 是否编码. Defaults to False.
63+
64+ Returns:
65+ Union[str, bytes]: with_encode为True则返回为bytes否则为str
66+ """
4267 buffer = io .StringIO ()
4368 if self .comment is not None :
4469 for chunk in self ._LINE_SEP_EXPR .split (self .comment ):
@@ -57,8 +82,6 @@ def render(self, with_encode: bool = False) -> Union[str, bytes]:
5782 buffer .write (self ._DEFAULT_SEPARATOR )
5883
5984 if self .retry is not None :
60- if not isinstance (self .retry , int ):
61- raise TypeError ("retry argument must be int" )
6285 buffer .write ("retry: {}" .format (self .retry ))
6386 buffer .write (self ._DEFAULT_SEPARATOR )
6487
@@ -69,7 +92,19 @@ def render(self, with_encode: bool = False) -> Union[str, bytes]:
6992 return result
7093
7194 @classmethod
72- def from_content (clz , content : Union [str , bytes ], strict : bool = False ) -> "SSE" :
95+ def from_content (clz , content : Union [str , bytes ], * , strict : bool = False ) -> "SSE" :
96+ """从字符串或者字节流中解析出sse消息.
97+
98+ Args:
99+ content (Union[str, bytes]): 待解析的内容
100+ strict (bool, optional): 严格模式,校验结尾是否为`\r \n \r \n `. Defaults to False.
101+
102+ Raises:
103+ ValueError: not end with `\r \n \r \n `
104+
105+ Returns:
106+ [SSE]: sse消息对象
107+ """
73108 if isinstance (content , bytes ):
74109 content = content .decode ("utf-8" )
75110 if strict :
@@ -82,6 +117,7 @@ def from_content(clz, content: Union[str, bytes], strict: bool = False) -> "SSE"
82117 retry = 0
83118 comment = ""
84119 lines = content .strip ().split (clz ._DEFAULT_SEPARATOR )
120+ print (lines )
85121 for line in lines :
86122 if line .startswith (":" ):
87123 c = line [1 :].strip () + "\n "
0 commit comments