【问题标题】:Pass data from Python (flask framework) to javascript将数据从 Python(flask 框架)传递到 javascript
【发布时间】:2014-10-23 13:18:37
【问题描述】:

我尝试将数据(确切地说是路径或 url)从烧瓶传递到 javascript。但它不承认我的变量。 在服务器端:它上传一个文件,处理这个文件,然后创建和保存许多图像。当我尝试将路径传递给使用 three.js 库的 javascript 文件时,它不会。

@app.route('/upload', methods=['POST'])
def upload_file():
    print('coucou')
    if request.method == 'POST':
        file = request.files['file']
        print(file)
        # if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        print(filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        path = UPLOAD_FOLDER + filename
        fits_reader = FitsReader.FitsReader()
        fits_reader.open_file(path)
        cube_faces = ['/home/morban/essaiserver/cube3D/CubeX.PNG', '/home/morban/essaiserver/cube3D/CubeY.PNG', '/home/morban/essaiserver/cube3D/CubeZ.PNG']
    return render_template('index.html', cube_faces=cube_faces)




for (var i = 0; i < 3; i++) {
        switch (i) {
            case 0:
                texture[i] = new THREE.ImageUtils.loadTexture('{{ cube_faces[0] }}');
                console.log('{{ cube_faces[0] }}')
                break;
            case 1:
                texture[i] = new THREE.ImageUtils.loadTexture('{{ cube_faces[1] }}');
                break;
            case 2:
                texture[i] = new THREE.ImageUtils.loadTexture('{{ cube_faces[2] }}');
                break;
            }

【问题讨论】:

  • 您是否尝试过将所需的数据放在一个 txt 文件中,然后通过 Ajax 调用访问它?这有点多,但如果没有其他方法,至少我们知道会。此外,flask 是否具有像 Django 这样的脚本功能,您可以在其中打印视图中的服务器端变量?

标签: javascript python flask


【解决方案1】:

javascript必须在模板文件中,不包含有脚本源。

如果包含,您可以使其具有函数或“类”并像这样使用它:

   (function($) {
    var texture = new LoadTexture(
                '#filter_form',
                {{ cube_faces | tojson | safe }}
            );
    })(jQuery); 

您可以/应该通过 cube_fase 有 json 并将其过滤到 Jinja2 上的安全。

【讨论】:

    猜你喜欢
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 2023-03-25
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多