1
0
Fork 0
forked from s3lph/matemat

Catch potential file-magic exception.

This commit is contained in:
s3lph 2018-07-20 00:49:29 +02:00
parent e2f2ab7727
commit 8598daf3b0

View file

@ -329,8 +329,14 @@ class HttpHandler(BaseHTTPRequestHandler):
headers['Content-Length'] = str(len(data)) headers['Content-Length'] = str(len(data))
# If the pagelet did not set its own Content-Type header, use libmagic to guess an appropriate one # If the pagelet did not set its own Content-Type header, use libmagic to guess an appropriate one
if 'Content-Type' not in headers: if 'Content-Type' not in headers:
try:
filemagic: magic.FileMagic = magic.detect_from_content(data) filemagic: magic.FileMagic = magic.detect_from_content(data)
headers['Content-Type'] = f'{filemagic.mime_type}; charset={filemagic.encoding}' mimetype: str = filemagic.mime_type
charset: str = filemagic.encoding
except ValueError:
mimetype = 'application/octet-stream'
charset = 'binary'
headers['Content-Type'] = f'{mimetype}; charset={charset}'
# Send all headers set by the pagelet # Send all headers set by the pagelet
for name, value in headers.items(): for name, value in headers.items():
self.send_header(name, value) self.send_header(name, value)
@ -369,9 +375,13 @@ class HttpHandler(BaseHTTPRequestHandler):
# File read successfully, send 'OK' header # File read successfully, send 'OK' header
self.send_response(200) self.send_response(200)
# Guess the MIME type and encoding using libmagic # Guess the MIME type and encoding using libmagic
try:
filemagic: magic.FileMagic = magic.detect_from_filename(filepath) filemagic: magic.FileMagic = magic.detect_from_filename(filepath)
mimetype: str = filemagic.mime_type mimetype: str = filemagic.mime_type
charset: str = filemagic.encoding charset: str = filemagic.encoding
except ValueError:
mimetype = 'application/octet-stream'
charset = 'binary'
# Send content type and length header # Send content type and length header
self.send_header('Content-Type', f'{mimetype}; charset={charset}') self.send_header('Content-Type', f'{mimetype}; charset={charset}')
self.send_header('Content-Length', str(len(data))) self.send_header('Content-Length', str(len(data)))