don't block db while serving images

This commit is contained in:
j 2019-01-30 18:00:58 +05:30
parent f24e095987
commit 0234b8dffb
1 changed files with 41 additions and 40 deletions

View File

@ -121,55 +121,56 @@ class Handler(http.server.SimpleHTTPRequestHandler):
else:
id = None
if id and len(id) == 32 and id.isalnum():
path = None
data = None
with db.session():
if preview:
from item.icons import get_icon_sync
try:
data = get_icon_sync(id, 'preview', 512)
content = get_icon_sync(id, 'preview', 512)
except:
data = None
if data:
content = None
if content:
self.send_response(200, 'ok')
self.send_header('Content-type', 'image/jpg')
mimetype = 'image/jpg'
else:
self.send_response(404, 'Not Found')
self.send_header('Content-type', 'text/plain')
data = b'404 - Not Found'
content_length = len(data)
self.send_header('Content-Length', str(content_length))
self.end_headers()
self.write_with_limit(data, content_length)
return
file = item.models.File.get(id)
if not file:
self.send_response(404, 'Not Found')
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(b'404 - Not Found')
return
path = file.fullpath()
mimetype = {
'epub': 'application/epub+zip',
'pdf': 'application/pdf',
'txt': 'text/plain',
}.get(path.split('.')[-1], None)
self.send_response(200, 'OK')
self.send_header('Content-Type', mimetype)
self.send_header('X-Node-Protocol', settings.NODE_PROTOCOL)
if mimetype == 'text/plain':
with open(path, 'rb') as f:
content = f.read()
content = self.gzip_data(content)
content_length = len(content)
content = b'404 - Not Found'
mimetype = 'text/plain'
else:
content = None
content_length = os.path.getsize(path)
self.send_header('Content-Length', str(content_length))
self.end_headers()
if content:
self.write_with_limit(content, content_length)
else:
self.write_file_with_limit(path, content_length)
file = item.models.File.get(id)
if file:
path = file.fullpath()
mimetype = {
'epub': 'application/epub+zip',
'pdf': 'application/pdf',
'txt': 'text/plain',
}.get(path.split('.')[-1], None)
self.send_response(200, 'OK')
else:
self.send_response(404, 'Not Found')
content = b'404 - Not Found'
mimetype = 'text/plain'
self.send_header('Content-Type', mimetype)
self.send_header('X-Node-Protocol', settings.NODE_PROTOCOL)
if mimetype == 'text/plain' and path:
with open(path, 'rb') as f:
content = f.read()
content = self.gzip_data(content)
content_length = len(content)
elif path:
content = None
content_length = os.path.getsize(path)
elif content:
content_length = len(content)
else:
content_length = 0
self.send_header('Content-Length', str(content_length))
self.end_headers()
if content:
self.write_with_limit(content, content_length)
elif path:
self.write_file_with_limit(path, content_length)
elif len(parts) == 2 and parts[1] == 'log':
self._changelog()
else: