You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python向Flask传递列表且不暴露于HTML源码中?

解决方案

方法1:通过AJAX异步请求获取数据(推荐)

这种方式不会把列表内容直接输出到HTML源码中,而是在页面加载完成后由JavaScript主动向后端请求数据,完全匹配你的需求。

后端Flask代码

添加一个专门提供数据的API路由:

from flask import jsonify

@app.route('/api/trends')
def get_trends():
    # 直接传入你已准备好的trends列表
    return jsonify(trends)

前端JavaScript代码

在HTML的<script>标签中使用fetch请求数据:

document.addEventListener('DOMContentLoaded', function() {
    fetch('/api/trends')
        .then(response => response.json())
        .then(data => {
            // 此处的data就是目标trends列表,可直接用于业务逻辑
            console.log(data);
            // 示例:调用自定义处理函数
            // processTrendsData(data);
        })
        .catch(error => console.error('数据获取失败:', error));
});

方法2:加密后嵌入模板(适合非敏感但需隐藏原始内容的场景)

如果不想额外新增API接口,可以将列表加密后嵌入模板,前端JS解密后使用。这种方式下HTML源码只会显示加密后的字符串,不会暴露原始列表。

后端Flask代码

import json
from cryptography.fernet import Fernet

# 注意:密钥应配置在环境变量或配置文件中,此处仅做示例
key = Fernet.generate_key()
cipher_suite = Fernet(key)

@app.route('/map')
def map_page():
    # 将列表转为JSON字符串后加密
    encrypted_trends = cipher_suite.encrypt(json.dumps(trends).encode())
    # 传递加密数据和解密密钥到模板
    return render_template(
        'map.html', 
        encrypted_trends=encrypted_trends.decode(), 
        key=key.decode()
    )

前端JavaScript代码

document.addEventListener('DOMContentLoaded', function() {
    // 从模板获取加密数据与密钥
    const encryptedData = "{{ encrypted_trends | safe }}";
    const key = "{{ key | safe }}";
    
    // 借助Fernet的JS实现解密(需提前引入fernet.js库)
    const cipher = new Fernet(key);
    const decryptedData = cipher.decrypt(encryptedData);
    const trends = JSON.parse(decryptedData);
    
    // 解密后即可使用trends列表
    console.log(trends);
});

注意:该方式需要前端引入Fernet的JS实现,且密钥若直接嵌入模板仍存在被逆向解析的可能,更适合非敏感数据场景。

方法3:用Session暂存敏感数据

如果列表包含敏感信息,可以先存入Flask的Session中,前端通过接口请求时再从Session取出返回:

后端Flask代码

from flask import session, jsonify

@app.route('/map')
def map_page():
    # 将列表存入Session(需提前配置SECRET_KEY)
    session['trends'] = trends
    return render_template('map.html')

@app.route('/api/get-trends')
def get_trends_from_session():
    # 取出数据后立即从Session删除,避免重复获取
    trends = session.pop('trends', [])
    return jsonify(trends)

前端JavaScript代码

与方法1的前端代码一致,仅需将请求地址替换为/api/get-trends即可。


内容的提问来源于stack exchange,提问作者Zvi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:20:44