I got some understanding of how to create a webpage using Python Flask to display a png image from these webpages:
- Where does flask look for image files?
- Flask doesn't render any image
- Change static folder from config in Flask
This is my Python Flask code:
template_dir = "/home/maxloo/pyrest/"
static_dir = "/home/maxloo/pyrest/static"
app = Flask(__name__, template_folder=template_dir, static_url_path=static_dir)
@app.route("/petri/<uuid>")
def getPetriFile(uuid):
dirPath = template_dir + "temp/workdir/" + uuid + "/petri/"
dotPath = dirPath + "LATEST"
petriFolder = static_dir + "/temp/workdir/" + uuid + "/petri/"
if not os.path.exists(petriFolder):
Path(petriFolder).mkdir(parents=True, exist_ok=True)
petriPath = petriFolder + "LATEST.png"
templatePetriPath = "/temp/workdir/" + uuid + "/petri/LATEST.png"
return render_template("image.html", user_image = templatePetriPath)
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src="{{ user_image }}" alt="User Image">
<object type="image/png" data="{{ user_image }}">
</object>
</body>
</html>
However, the web page could not display the image. Can anyone help? The images I use and the folders that contain them are dynamically generated. Only the template parent directory is static.
I've amended my code to include static_url_path
, but it still did not display the image.
This is the output of running the tree
command:
┌─[20220629-08:57:28] [maxloo@:~/pyrest/static]
└─[0] <> tree
.
├── LATEST.png
└── temp
└── workdir
└── 28d023bd-84e7-445a-8488-1e8aeb1fd50a
└── petri
└── LATEST.png
4 directories, 2 files
I've even tried this Python Flask code:
template_dir = "/home/maxloo/pyrest/"
static_dir = "/home/maxloo/pyrest/static/"
app = Flask(__name__, template_folder=template_dir, static_url_path=static_dir)
app.static_url_path = static_dir
for rule in app.url_map.iter_rules('static'):
app.url_map._rules.remove(rule)
app.url_map._rules_by_endpoint['static'] = []
app.view_functions["static"] = None
app.add_url_rule(static_dir + "LATEST.png",
endpoint='static',
view_func=app.send_static_file)
@app.route("/petri/<uuid>")
def getPetriFile(uuid):
petriPath = static_dir + "LATEST.png"
return render_template("image.html", user_image = static_dir)
I've left out most of the code in def getPetriFile(uuid):
because they are only required for the generation of the dynamic image file LATEST.png.