I'm trying to add backend support to my React project using Flask.
In my python file I'm trying to send information from my sqlite3 database:
@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
My relevant HTML in which I receive the info
object:
<div id="root" data-info={{info}}></div>
And then I try to parse it and pass to my React app in my (external) js file:
const info = document.getElementById('root').dataset.info;
var allInfo = info ? JSON.parse(info) : null;
My problem is that in my HTML the info
object somehow returns from render_template
as a messed up junk (puts the string from info
as weird attributes), I think because of an unnecessary addition of double quotation mark (viewed using chrome devtools):
<div id="root" data-info="[[1," "abc",="" "2021-01-25="" 14:13:02",="" 1,="" "user",="" "name=""]]=""></div>
Why does this happen? I tried adding pipes such as |tojson
or |safe
but they were of no help.
Any assistance would be appreciated.
Edit:
I've managed to at least receive everything in data-info
by altering the python file:
@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
Now I managed to receive it as a non-friendly, non-json text:
<div id="root" data-info="[1, u0027abcu0027, datetime.datetime(2021, 1, 26, 7, 55, 9), 1, u0027useru0027, u0027nameu0027]"></div>
Which gives me what I want, but now I need to regex it to properly digest it in my React app. I'm sure there's a better way to handle this.
question from:
https://stackoverflow.com/questions/65886963/jinja-adds-unnecessary-double-quotations-when-sending-to-data-attribute