Jinja在发送到data*属性时添加了不必要的双引号

2024-05-29 05:55:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Flask向React项目添加后端支持

在python文件中,我试图从sqlite3数据库发送信息:

@bp.route('/')
def index():
    #get_db() is a function defined elsewhere to connect to the database
    db = get_db()
    posts = db.execute(
        'SELECT """relevant fields"""'
        ' FROM """relevant columns"""'
        ' ORDER BY created DESC'
    ).fetchall()

    #thats to my knowledge the best solution to not return a sqlite3.Row object:
    info = []
    for row in rows:
        info.append(list(row))  

    return render_template('/index.html', info=json.dumps(info, default=str)) #default=str to handle date object

接收info对象的相关HTML:

<div id="root" data-info={{info}}></div>

然后我尝试解析它并将其传递到我(外部)js文件中的React应用程序:

const info = document.getElementById('root').dataset.info;
var allInfo = info ? JSON.parse(info) : null;

我的问题是,在我的HTML中,info对象以某种方式从render_template返回,作为一个乱七八糟的垃圾(将info的字符串作为奇怪的属性),我认为这是因为不必要地添加了双引号(使用chrome devtools查看):

<div id="root" data-info="[[1," "abc",="" "2021-01-25="" 14:13:02",="" 1,="" "user",="" "name=""]]=""></div>

为什么会发生这种情况?我尝试添加管道,如|tojson|safe,但没有任何帮助

任何协助都将不胜感激


编辑:

通过更改python文件,我至少在data-info中接收到了所有内容:

@bp.route('/')
def index():
    #get_db() is a function defined elsewhere to connect to the database
    db = get_db()
    posts = db.execute(
        'SELECT """relevant fields"""'
        ' FROM """relevant columns"""'
        ' ORDER BY created DESC'
    ).fetchall()

    #thats to my knowledge the best solution to not return a sqlite3.Row object:
    info = ""
    for row in rows:
        info+=(str(list(row))) #replaced info from list to string  

    return render_template('/index.html', info) #removed the json dump

现在我设法以非友好、非json文本的形式接收它:

<div id="root" data-info="[1, \u0027abc\u0027, datetime.datetime(2021, 1, 26, 7, 55, 9), 1, \u0027user\u0027, \u0027name\u0027]"></div>

这给了我想要的,但现在我需要正则化它,以便在我的React应用程序中正确地消化它。我确信有更好的方法来处理这个问题


Tags: 文件thetodivinfodbdataget
1条回答
网友
1楼 · 发布于 2024-05-29 05:55:17

传递到render_template函数的惯用dict:

return render_template('/index.html', info)

在模板使用tojson筛选两次时,它必须帮助您:

<div id="root" data-info={{ info | tojson | tojson }}></div>

输出将是:

<div id="root" data-info="{\\"example\\": 1}"></div>

相关问题 更多 >

    热门问题