Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update t0pic.py #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 18 additions & 23 deletions t0pic.py
Expand Up @@ -96,49 +96,44 @@ def index():
def new():
try:
if 'pic' not in request.files or request.files['pic'].filename == '':
print('No file part')
abort(400)

print("No file part")
abort(400) # No file was uploaded
pic = request.files['pic']

if pic.mimetype not in ['image/png', 'image/jpeg', 'image/gif', 'application/octet-stream']:
print(f'Unsupported image format: {pic.mimetype}')
abort(400)

if pic.seek(0, 2) > MAX_FILE_SIZE: # Move to end to get file size
print(f'File size exceeds maximum allowed limit: {pic.tell()} bytes')
abort(413)
if pic.mimetype not in ['application/octet-stream', 'image/png', 'image/jpeg', 'image/gif']:
print(f"Unsupported image format: {pic.mimetype}")
abort(400) # Consider using a more specific status code or returning an error message
if pic.seek(0, 2) > MAX_ALLOWED_SIZE: # Move to end to get file size
print(f"File size exceeds maximum allowed limit: {pic.tell()} bytes")
abort(413) # Payload Too Large
pic.seek(0) # Reset file pointer

nid = new_id()
while nid in [p.stem for p in DATA_FOLDER.iterdir()]:
while nid in [p.stem for p in PICS.iterdir()]:
nid = new_id()

pic = Image.open(pic.stream)

pic = Image.open(pic.stream) # Use .stream to read directly from Flask file storage
if pic.format == 'PNG':
ext = '.png'
elif pic.format == 'JPEG':
ext = '.jpg'
elif pic.format == 'GIF':
ext = '.gif'
else:
print(f'Unsupported image format: {pic.format}')
print(f"Unsupported image format: {pic.format}")
abort(400)

filename = nid + ext
pic.thumbnail([MAX_SIZE, MAX_SIZE], Image.Resampling.LANCZOS)
pic.save(DATA_FOLDER / filename)

if pic.format == 'GIF':
# Handle GIFs separately to preserve animation
pic.save(PICS / filename, save_all=True)
else:
pic.thumbnail([MAX_SIZE, MAX_SIZE], Image.Resampling.LANCZOS)
pic.save(PICS / filename) # Use pathlib's / operator for path concatenation
print(f'Adding pic {nid}{ext}')

url = f'{URL}/{nid}{ext}'
if 'web' in request.form:
return redirect(url)
else:
return f'{url}\n'
except Exception as e:
print(f'Error processing image upload: {e}')
print(f"Error processing image upload: {e}")
abort(400)

if __name__ == '__main__':
Expand Down