MCPcopy
hub / github.com/django/django / encode_file

Function encode_file

django/test/client.py:340–367  ·  view source on GitHub ↗
(boundary, key, file)

Source from the content-addressed store, hash-verified

338
339
340def encode_file(boundary, key, file):
341 def to_bytes(s):
342 return force_bytes(s, settings.DEFAULT_CHARSET)
343
344 # file.name might not be a string. For example, it's an int for
345 # tempfile.TemporaryFile().
346 file_has_string_name = hasattr(file, "name") and isinstance(file.name, str)
347 filename = os.path.basename(file.name) if file_has_string_name else ""
348
349 if hasattr(file, "content_type"):
350 content_type = file.content_type
351 elif filename:
352 content_type = mimetypes.guess_type(filename)[0]
353 else:
354 content_type = None
355
356 if content_type is None:
357 content_type = "application/octet-stream"
358 filename = filename or key
359 return [
360 to_bytes("--%s" % boundary),
361 to_bytes(
362 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)
363 ),
364 to_bytes("Content-Type: %s" % content_type),
365 b"",
366 to_bytes(file.read()),
367 ]
368
369
370class RequestFactory:

Callers 3

test_file_encodingMethod · 0.90
encode_multipartFunction · 0.85

Calls 2

to_bytesFunction · 0.85
readMethod · 0.45