0

I want to send a variable value to python from flask html/js through url_for().

Python Code :

@app.route('/video_feed/<device>')
def video_feed(device):
    # return the response generated along with the specific media
    # type (mime type)
    print(device)
    try:
        return Response(gen(int(device)),mimetype = "multipart/x-mixed-replace; boundary=frame")
    except Exception as e:
        return Response(gen(device),mimetype = "multipart/x-mixed-replace; boundary=frame")

Desired in flask html file:

data.value = 0;
image.src = "{{ url_for('video_feed', device=data.value)}}";

But it does not work, I get the error:

jinja2.exceptions.UndefinedError: 'data' is undefined

This does work, however I can't use the variable data.value in url_for() :

image.src = "{{ url_for('video_feed', device=0)}}";

I have tried several different things like:

image.src = "{{ url_for('video_feed', device=${data.value})}}";
image.src = "{{ url_for('video_feed', device=$data.value)}}";
image.src = "{{ url_for('video_feed', device=%s)}}", data.value;

But nothing seems to work. My javascript is a bit rusty.

Any help would be appreciated!

Cheers!

1 Answer 1

1

url_for is expanded on the server side, before the page gets sent to the browser and well before JavaScript runs.

If you know the number (for device/data.value) at page generation time, pass it in to the template via render_template().

If, however, you don't know the value until after the page is rendered, you're going to need to construct the img element from JavaScript.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply. I do not know the value until after the page is rendered. This is my scenario. The Flask Website receive messeges via SocketIO in JSON format. The "data" variable above is that JSON object. The field "value" contains an address for a captureable device. For each incoming JSON object I want to create a new <img> with src=url_for(...). As i mention this works when I'm not using variables. I agree that it's because of when the page is rendered. Can I do this some other way? I have a couple of ideas like, ajax? or proxy-server or restructure to solve this on the python side.
Oh, now I see what you mean the src generated by url_for() are replicable in js.
So there were really no need for me to use url_for(). Should just use image.src = "/video_feed/"+data.value;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.