Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a variable without reloading the page

Tags:

python

flask

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?

like image 594
fergusdawson Avatar asked Jan 15 '23 04:01

fergusdawson


1 Answers

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>
like image 200
Sean Vieira Avatar answered Jan 17 '23 19:01

Sean Vieira