I have a list of image names loaded with flask, which I am rendering to an html template, so that the page displays the image. The only way I can seem to alter the image list (ie. add an image to it) is to make a view which contains code to change the list, but in order to access the view you have to reload the whole page again. Is there any way I can alter the list with flask without having to reload the whole page?
Jakob Bowyer is absolutely correct - use ajax:
from flask import jsonify
from werkzeug.security import safe_join
@app.route("/gallery")
def gallery():
images = get_images_from_dir("some/base/path/*.jpg")
return render_template("gallery.html", images=images)
@app.route("/search/images", methods=["POST"])
def search_images():
glob_path = request.form["image_query"]
glob_path = safe_join("/some/base/path", glob_path)
return jsonify(images=get_images_from_dir(glob_path))
Then in your template just hit the appropriate endpoint:
<!-- snip -->
<script>
// jQuery here - you can use anything you want :-)
$.post({
url: "{{ url_for("search_images") }}",
success: function(data) {
console.log(data);
},
error: function() { console.log("Error", arguments); }
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With