Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

32 Commits

Repository files navigation

Downloads

python-magic-file

Small Python module to aid developers in getting file extensions from files.

Purpose

The main motivation behind this package is to easily get the file extension from given file instead of trusting the arbitrary file extension in the filename, for example in a web application which accepts file uploads.

Usage

Some examples on how to use this module.

Get extension from file

frompython_magic_fileimportMagicFilefile_path='path/to/file'withopen(file_path'rb') asf:
magic_file=MagicFile(f)
extension=magic_file.get_extension()

Get extensions from file

frompython_magic_fileimportMagicFilefile_path='path/to/file'withopen(file_path'rb') asf:
magic_file=MagicFile(f)
extensions=magic_file.get_extensions()

Register unknown/non-standard mimetypes

There may be some cases where get_extension() emits a following warning:

UserWarning: File extension for mimetype "video/x-m4v" is None, consider adding an extension for this mimetype using MagicFile.

We have to register file extension using MagicFile.add_type_to_mimetypes_module for video/x-m4v so get_extension() returns the registered extension instead of None.

MagicFile.add_type_to_mimetypes_module simply just calls mimetypes.add_type.

frompython_magic_fileimportMagicFile# A dictionary of mimetype/extension pairsnew_types= {'video/x-m4v': '.m4v'}
formimetype, extensioninnew_types.items():
MagicFile.add_type_to_mimetypes_module(mimetype, extension)
withopen('path/to/m4v-file.m4v', 'rb') asf:
magic_file=MagicFile(f)
extension=magic_file.get_extension() # .m4v

Get human readable name for file

frompython_magic_fileimportMagicFilefile_path='path/to/file.txt'withopen(file_path'rb') asf:
magic_file=MagicFile(f)
human_readable_name=magic_file.get_name() # ASCII text, with no line terminators

Usage with Flask

importosfromflaskimportFlask, request, abortfrompython_magic_fileimportMagicFilefromwerkzeug.utilsimportsecure_filenamefromwerkzeug.securityimportsafe_joinapp=Flask(__name__)
# Allowed extensions for file uplaodUPLOAD_ALLOWED_EXTENSIONS= ('.jpg', '.jpeg', '.png')
@app.post('/upload')defupload_file():
uploaded_file=request.files.get('file')
ifuploaded_fileisNone:
abort(400)
extension=MagicFile(uploaded_file.stream).get_extension()
ifextensionnotinUPLOAD_ALLOWED_EXTENSIONS:
abort(400)
filename, _=os.path.splitext(secure_filename(uploaded_file.filename))
save_path=safe_join(os.getcwd(), filename+extension)
uploaded_file.save(save_path)
return'OK'if__name__=='__main__':
app.run()

About

Small Python module to aid developers in getting file extensions from files securely using libmagic.

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Used by

Contributors

Languages