我正在尝试使用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应用程序中正确地消化它。我确信有更好的方法来处理这个问题
传递到
render_template
函数的惯用dict:在模板使用
tojson
筛选两次时,它必须帮助您:输出将是:
相关问题 更多 >
编程相关推荐