2025-09-15_parsing-multipart-form-data.html
001|
002|
003|
004|
005| from cgi import FieldStorage
006|
007| if __name__ == '__main__':
008| form = FieldStorage()
009| ...
010|
011|
012| from sys import stdin
013| from os import environ
014| from urllib import parse
015|
016| if __name__ == '__main__':
017|
018| qs = environ.get('QUERY_STRING', '')
019| get_dict = parse.parse_qs(qs)
020|
021|
022| post_len = int(environ.get('CONTENT_LENGTH', 0))
023| post_txt = stdin.read(post_len)
024| post_dict = parse.parse_qs(post_txt)
025|
026| form = dict(**get_dict, **post_dict)
027| params = {}
028| for name in sorted(form):
029| value = form[name]
030|
031| if 1 < len(value):
032| for ix,v in enumerate(value, start=1):
033| params[f'{name}-{ix}'] = v
034|
035| else:
036| params[name] = value[0]
037| ...
038|
039|
040| if __name__ == '__main__':
041| ...
042| for name in sorted(form):
043| ...
044|
045| if name == 'fn':
046| fobj = form['fn']
047| params['fn'] = fobj.filename
048| params['fp'] = fobj.file
049| ...
050| ...
051|
052|
053| fn = kwargs['fn']
054| bs = kwargs['fp'].read()
055| ...
056|
057|
058| txt = 'Content-Disposition: form-data; name="fn"; filename="foo.py"'
059|
060| class MimeHeader (tuple):
061| '''\
061| MIME Header class. Parses text to a defined tuple.
061|
061| Expected text has the syntax:
061| <name>: <text> [; name=value [; ...]]
061|
061| Created tuple is:
061| (name, text, fields)
061|
061| Properties:
061| name -field name
061| text -field text
061| fields -dictionary of name:value pairs
061|
061| Methods:
061| str(obj) -printable version
061| repr(obj) -debugging version
061| '''
062| def __new__ (cls, text):
063| '''New MimeHeader instance.'''
064|
065|
066| parts = text.partition(': ')
067| if parts[1] != ': ':
068| ValueError(f'Invalid MIME Header (no ": "): "{text}"')
069|
070|
071| subparts = parts[2].split('; ')
072| value = subparts[0]
073|
074| fields = {}
075| for subp in subparts[1:]:
076|
077| key,val = subp.split('=', maxsplit=1)
078|
079| fields[key] = val.strip('"')
080|
081|
082| return super().__new__(cls, (parts[0], value, fields))
083|
084| @property
085| def name (self): return self[0]
086|
087| @property
088| def text (self): return self[1]
089|
090| @property
091| def fields (self): return self[2]
092|
093| def __str__ (self):
094| return f'{self.name}: {self.text}'
095|
096| def __repr__ (self):
097| return f'<{type(self).__name__} @{id(self):08x}>'
098|
099|
100| if __name__ == '__main__':
101| hdr = MimeHeader(txt)
102| print(f'Header: {hdr} {hdr!r}')
103| print(f'Header Name: {hdr.name}')
104| print(f'Header Text: {hdr.text}')
105| print('Header Fields:')
106| for nam,val in hdr.fields.items():
107| print(f'> {nam}: {val}')
108| print()
109|
110|
111| from examples import MimeHeader
112|
113| EOL = ord('\n')
114| CR = ord('\r')
115| DASH = ord('-')
116|
117| def parse_multipart_form (content_type:str, byte_string:bytes) -> tuple:
118| '''\
118| Parse Multipart Form Data.
118|
118| Arguments:
118| content_type -content header text
118| byte_string -form data bytes
118|
118| Returns:
118| tuple: (form, filename, filetype, filedata)
118|
118| Note: the last three field will be None if no file data.
118| '''
119| form = {}
120| parthdrs = {}
121| content = []
122| buf = []
123| state = 'prefix'
124| boundary = None
125|
126|
127| ix = content_type.index('boundary=') + len('boundary=')
128| boundary = content_type[ix:].lstrip('-')
129|
130|
131| for bx in byte_string:
132|
133| if state == 'prefix':
134|
135| if bx == DASH:
136| buf.append(bx)
137| continue
138|
139| if len(buf) < 6:
140| raise SyntaxError(f'Expected six hyphens, not {len(buf)}.')
141|
142| buf = [bx]
143| state = 'sep'
144| continue
145|
146| if state == 'sep':
147|
148| if bx == EOL:
149| sep_str = ''.join(chr(b) for b in buf)
150| if not sep_str.startswith(boundary):
151| raise SyntaxError(f'Invalid Separator: "{sep_str}"')
152| buf = []
153| parthdrs = {}
154| state = 'part.start'
155| continue
156|
157| if bx == CR:
158| continue
159|
160| buf.append(bx)
161| continue
162|
163| if state == 'part.start':
164|
165| if bx == EOL:
166|
167| content = []
168| state = 'part.data'
169| continue
170|
171| if bx == CR:
172| continue
173|
174| buf = [bx]
175| state = 'part.hdr'
176| continue
177|
178| if state == 'part.hdr':
179|
180| if bx == EOL:
181| txt = ''.join(chr(b) for b in buf)
182| hdr = MimeHeader(txt)
183| parthdrs[hdr.name.lower()] = hdr
184| state = 'part.start'
185| continue
186|
187| if bx == CR:
188| continue
189|
190| buf.append(bx)
191| continue
192|
193| if state == 'part.data':
194|
195| if bx == DASH:
196| buf = [bx]
197| state = 'test.prefix'
198| continue
199|
200| content.append(bx)
201| continue
202|
203| if state == 'test.prefix':
204|
205| if bx != DASH:
206|
207| if len(buf) != 6:
208|
209| content.extend(buf)
210| content.append(bx)
211| state = 'part.data'
212| continue
213|
214| buf = [bx]
215| state = 'test.sep'
216| continue
217|
218| buf.append(bx)
219| continue
220|
221| if state == 'test.sep':
222|
223| if bx == EOL:
224| txt = (''.join(chr(c) for c in buf)).strip()
225| if txt != boundary:
226|
227| content.extend(buf)
228| content.append(bx)
229| state = 'part.data'
230| continue
231|
232| cdisp = parthdrs['content-disposition']
233| name = cdisp.fields['name']
234|
235| form[name] = bytes(content[0:-2])
236|
237| form[f'{name}.disp'] = cdisp
238|
239| if 'content-type' in parthdrs:
240|
241| form[f'{name}.type'] = parthdrs['content-type']
242|
243| buf = []
244| parthdrs = {}
245| state = 'part.start'
246| continue
247|
248| buf.append(bx)
249| continue
250|
251|
252| filedata, filename, filetype = None,None,None
253| for name in form:
254| if name == 'fn':
255| filedata = form['fn']
256| filetype = form['fn.type'].text
257| filename = form['fn.disp'].fields['filename']
258| if filetype.startswith('text'):
259| filedata = str(filedata, encoding='utf8')
260| continue
261|
262|
263| if '.' not in name:
264| txt = form[name]
265| if isinstance(txt,bytes):
266| form[name] = str(txt, encoding='utf8')
267|
268| form['fn.name'] = filename
269| return (form, filename, filetype, filedata)
270|
271|
272| from sys import argv
273| from examples import parse_multipart_form
274|
275| FName = r'C:\Demo\Python\multipart-1.txt'
276| CType = r'multipart/form-data; boundary=----WebKitFormBoundaryFvgrhoe2FqQdLu4J'
277|
278| def test_parser (file_name:str, content_type:str) -> tuple:
279| '''Function to exercise Multipart parser.'''
280|
281|
282| fp = open(file_name, mode='rb')
283| try:
284| data = fp.read()
285| print(f'loaded: {file_name}')
286| print(f'bytes: {len(data)}')
287| print()
288| except:
289| raise
290| finally:
291| fp.close()
292|
293|
294| form,fname,ftype,fdata = parse_multipart_form(content_type, data)
295|
296|
297| for key in sorted(form):
298| val = form[key]
299|
300| if key == 'fn':
301| print(f'{key}: <filedata>')
302| continue
303|
304| if isinstance(val, str):
305| print(f'{key}: {val}')
306| continue
307|
308| print(f'{key}: {form[key].text}')
309|
310| print()
311|
312| return (form, fname, ftype, fdata)
313|
314| if __name__ == '__main__':
315| print(f'autorun: {argv[0]}')
316|
317| file_name = argv[1] if 1 < len(argv) else FName
318| content_type = argv[2] if 2 < len(argv) else CType
319|
320| print()
321| form,fname,ftype,fdata = test_parser(file_name, content_type)
322| print()
323|
324|
325|