Fixed images, now using temp files
This commit is contained in:
parent
fc99c3f95f
commit
9370f0144e
33
app.py
33
app.py
@ -2,8 +2,10 @@ import io
|
||||
import tempfile
|
||||
import subprocess
|
||||
import requests
|
||||
from flask import Flask, render_template_string, request, send_from_directory
|
||||
import base64
|
||||
from flask import Flask, render_template_string, request, send_from_directory, session
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import os
|
||||
import re
|
||||
import argparse
|
||||
|
||||
@ -322,6 +324,14 @@ HTML_FORM = '''
|
||||
</div>
|
||||
'''
|
||||
|
||||
def remove_uploaded_img():
|
||||
path = session.pop('uploaded_img_path', None)
|
||||
if path and os.path.exists(path):
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def bleh_image_from_url(url):
|
||||
resp = requests.get(url, stream=True)
|
||||
resp.raise_for_status()
|
||||
@ -604,13 +614,30 @@ def index():
|
||||
userimg = request.files.get("userimg")
|
||||
uploaded_img_bytes = None
|
||||
if userimg and userimg.filename:
|
||||
uploaded_img_bytes = userimg.read()
|
||||
# Remove old temp file if present
|
||||
remove_uploaded_img()
|
||||
# Save new file to a temp location
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".catnote") as tmpf:
|
||||
userimg.save(tmpf)
|
||||
tmpf.flush()
|
||||
session['uploaded_img_path'] = tmpf.name
|
||||
tmpf.seek(0)
|
||||
uploaded_img_bytes = tmpf.read()
|
||||
elif 'uploaded_img_path' in session:
|
||||
path = session['uploaded_img_path']
|
||||
if os.path.exists(path):
|
||||
with open(path, "rb") as f:
|
||||
uploaded_img_bytes = f.read()
|
||||
else:
|
||||
# If file was deleted or missing, remove from session
|
||||
session.pop('uploaded_img_path', None)
|
||||
else:
|
||||
remove_uploaded_img()
|
||||
md = request.form["md"]
|
||||
image = render(md, uploaded_img_bytes)
|
||||
buf = io.BytesIO()
|
||||
image.save(buf, format="PNG")
|
||||
buf.seek(0)
|
||||
import base64
|
||||
img_data = base64.b64encode(buf.getvalue()).decode()
|
||||
# If print button pressed, send to driver
|
||||
if "print" in request.form:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user