【问题标题】:Flask send variable data to python through url_for()Flask 通过 url_for() 向 python 发送变量数据
【发布时间】:2020-02-26 23:44:11
【问题描述】:

我想通过 url_for() 从flask html/js 向python 发送一个变量值。

Python 代码:

@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")

在烧瓶 html 文件中需要:

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

但它不起作用,我收到错误:

jinja2.exceptions.UndefinedError: 'data' is undefined

这确实有效,但是我不能在 url_for() 中使用变量 data.value :

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

我尝试了几种不同的方法,例如:

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;

但似乎没有任何效果。我的 javascript 有点生疏了。

任何帮助将不胜感激!

干杯!

【问题讨论】:

    标签: javascript flask url-for


    【解决方案1】:

    url_for 在服务器端展开,在页面发送到浏览器之前以及 JavaScript 运行之前。

    如果您知道页面生成时的编号(对于device/data.value),请通过render_template() 将其传递给模板。

    但是,如果您在页面呈现之前不知道该值,则需要从 JavaScript 构造 img 元素。

    【讨论】:

    • 感谢您的回复。直到页面呈现后我才知道该值。这是我的场景。 Flask 网站通过 SocketIO 以 JSON 格式接收消息。上面的“数据”变量就是那个 JSON 对象。字段“值”包含可捕获设备的地址。对于每个传入的 JSON 对象,我想用 src=url_for(...) 创建一个新的 。正如我提到的,当我不使用变量时,这很有效。我同意这是因为页面呈现的时间。我可以通过其他方式做到这一点吗?我有几个想法,比如ajax?或代理服务器或重组以在 python 端解决这个问题。
    • 哦,现在我明白你的意思了 url_for() 生成的 src 可以在 js 中复制。
    • 所以我真的没有必要使用 url_for()。应该只使用image.src = "/video_feed/"+data.value;
    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 2018-07-26
    • 1970-01-01
    • 2018-05-31
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多