MCPcopy Index your code
hub / github.com/1Panel-dev/MaxKB / FileSerializer

Class FileSerializer

apps/oss/serializers/file.py:68–166  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

66
67
68class FileSerializer(serializers.Serializer):
69 file = UploadedFileField(required=True, label=_('file'))
70 meta = serializers.JSONField(required=False, allow_null=True)
71 source_id = serializers.CharField(
72 required=False, allow_null=True, label=_('source id'), default=FileSourceType.TEMPORARY_120_MINUTE.value
73 )
74 source_type = serializers.ChoiceField(
75 choices=FileSourceType.choices, required=False, allow_null=True, label=_('source type'),
76 default=FileSourceType.TEMPORARY_120_MINUTE
77 )
78
79 def upload(self, with_valid=True):
80 if with_valid:
81 self.is_valid(raise_exception=True)
82 meta = self.data.get('meta', None)
83 if not meta:
84 meta = {'debug': True}
85 file_id = meta.get('file_id', uuid.uuid7())
86 file = File(
87 id=file_id,
88 file_name=self.data.get('file').name,
89 meta=meta,
90 source_id=self.data.get('source_id') or FileSourceType.TEMPORARY_120_MINUTE.value,
91 source_type=self.data.get('source_type') or FileSourceType.TEMPORARY_120_MINUTE
92 )
93 file.save(self.data.get('file').read())
94 return f'./oss/file/{file_id}'
95
96 class Operate(serializers.Serializer):
97 id = serializers.UUIDField(required=True)
98 http_range = serializers.CharField(
99 required=False, allow_blank=True, allow_null=True, label=_('HTTP Range'),
100 help_text=_('HTTP Range header for partial content requests, e.g., "bytes=0-1023"')
101 )
102
103 def get(self, with_valid=True):
104 if with_valid:
105 self.is_valid(raise_exception=True)
106 file_id = self.data.get('id')
107 file = QuerySet(File).filter(id=file_id).first()
108 if file is None:
109 raise NotFound404(404, _('File not found'))
110 file_type = file.file_name.split(".")[-1].lower()
111 content_type = mime_types.get(file_type, 'application/octet-stream')
112 encoded_filename = urllib.parse.quote(file.file_name)
113 # 获取文件内容
114 file_bytes = file.get_bytes()
115 file_size = len(file_bytes)
116
117 response = None
118 if file_type in audio_types and self.data.get('http_range'):
119 response = self.handle_audio(file_size, file_bytes, content_type, encoded_filename)
120 if response:
121 return response
122
123 # 对于非范围请求或其他类型文件,返回完整内容
124 headers = {
125 'Content-Type': content_type,

Callers 15

postMethod · 0.90
postMethod · 0.90
upload_knowledge_fileMethod · 0.90
upload_tool_fileMethod · 0.90
upload_knowledge_fileMethod · 0.90
upload_tool_fileMethod · 0.90
upload_knowledge_fileMethod · 0.90
upload_tool_fileMethod · 0.90
upload_knowledge_fileMethod · 0.90

Calls 1

UploadedFileFieldClass · 0.90

Tested by

no test coverage detected