Skip to content
This repository has been archived by the owner on Jan 22, 2024. It is now read-only.

Commit

Permalink
优化GenerateResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
XiaoXinYo committed May 29, 2023
1 parent 3482aea commit d735d25
Showing 1 changed file with 27 additions and 22 deletions.
49 changes: 27 additions & 22 deletions module/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,34 @@ class GenerateResponse:
TYPE = Union[str, Response]

def __init__(self):
self.response = {}
self.onlyJSON = False

def json(self) -> TYPE:
responseJSON = json.dumps(self.response, ensure_ascii=False)
if self.stream:
self.code = 0
self.message = ''
self.data = None
self.streamFormat = False
self.streamResponse = False

def generate(self) -> TYPE:
responseJSON = json.dumps({
'code': self.code,
'message': self.message,
'data': self.data
}, ensure_ascii=False)
if self.streamFormat:
return f'data: {responseJSON}\n\n'
if self.streamResponse:
return Response(f'data: {responseJSON}\n\n', media_type='text/event-stream')
return Response(responseJSON, media_type='application/json')

def error(self, code: int, message: str, stream=False) -> TYPE:
self.response = {
'code': code,
'message': message,
'data': None
}
self.stream = stream
return self.json()
def error(self, code: int, message: str, streamFormat=False, streamResponse=False) -> TYPE:
self.code = code
self.message = message
self.streamFormat = streamFormat
self.streamResponse = streamResponse
return self.generate()

def success(self, data: Any, stream=False) -> TYPE:
self.response = {
'code': 200,
'message': 'success',
'data': data
}
self.stream = stream
return self.json()
def success(self, data: Any, streamFormat=False) -> TYPE:
self.code = 200
self.message = 'success'
self.data = data
self.streamFormat = streamFormat
return self.generate()

0 comments on commit d735d25

Please sign in to comment.