如何将列表从 flask 后端传递到 reactjs 前端?
how to pass a list from flask backend to a reactjs frontend?
我正在使用前同事编写的 restful API,当我使用 GET 从烧瓶 API 发送 json 到前端然后调用 json 中的值,我得到一个字符串而不是数组,列表如下所示
['ETH/BTC','LTC/BTC','BNB/BTC']
这是我认为与代码相关的内容
路线:
@bp.route('/fetch_bots_names', methods=['GET'])
def fetch_bots_names():
user_id = current_user.get_id()
bots = db.session.query(Bot).all()
viewable_bots = db.session.query(BotUserCanView).all()
user_bots = []
names = []
for x in bots:
ub = get_bot_data_as_dict(x)
if ub != None:
names.append(ub['name'])
return {'ok': True,
'msg':'Success',
'data': json.dumps(names)}, 200
获取数据的JS
const [botnames, setBotsNames] = useState([]);
if(savedStrats.length==0){
fetch('/auth/fetch_bots_names', {method: 'GET'})
.then(res => {return res.text()}).then(response => {
try {
let r = JSON.parse(response);
setBotsNames(r['data']);
} catch {
console.log(response);
}
});
}
正如我指出的那样,botnames 值是一个类似于示例的字符串,但我需要它作为一个数组(我认为是一个 JS 数组?)以便制作一个包含列表元素的下拉菜单,谢谢提前
您可以使用 jsonify 将数据转换为 JSON 格式并在响应中发送。
您可以使用关键字参数或传递字典。
documentation 清楚地解释了用法。
from flask import jsonify
@bp.route('/fetch_bots_names', methods=['GET'])
def fetch_bots_names():
bot_names = [bot.name for bot in Bot.query.all()]
return jsonify({
'ok': True,
'msg':'Success',
'data': bot_names
})
在 React 中,您可以像这样使用 Fetch Api。
fetch('/auth/fetch_bots_names')
.then(resp => resp.json())
.then(data => {
setBotsNames(data.data);
});
我还没有测试代码,但它应该可以工作。
如果您想发送更大的数据集,您可能需要查看 Flask-Marshmallow。
这是一个结合使用 Flask-Marshmallow 和 marshmallow-sqlalchemy.
的简单示例
from flask import Flask
from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(__name__)
db = SQLAlchemy(app)
ma = Marshmallow(app)
class Bot(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
class BotSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Bot
with app.app_context():
db.drop_all()
db.create_all()
bots = [Bot(name=f'bot-{i+1}') for i in range(5)]
db.session.add_all(bots)
db.session.commit()
@app.route('/bots')
def bots():
bots = Bot.query.all()
bot_schema = BotSchema(many=True)
bot_data = bot_schema.dump(bots)
return jsonify(data=bot_data)
查询结果如下所示。
{
"data": [
{
"id": 1,
"name": "name-1"
},
{
"id": 2,
"name": "name-2"
},
{
"id": 3,
"name": "name-3"
},
{
"id": 4,
"name": "name-4"
}
]
}
我正在使用前同事编写的 restful API,当我使用 GET 从烧瓶 API 发送 json 到前端然后调用 json 中的值,我得到一个字符串而不是数组,列表如下所示
['ETH/BTC','LTC/BTC','BNB/BTC']
这是我认为与代码相关的内容
路线:
@bp.route('/fetch_bots_names', methods=['GET'])
def fetch_bots_names():
user_id = current_user.get_id()
bots = db.session.query(Bot).all()
viewable_bots = db.session.query(BotUserCanView).all()
user_bots = []
names = []
for x in bots:
ub = get_bot_data_as_dict(x)
if ub != None:
names.append(ub['name'])
return {'ok': True,
'msg':'Success',
'data': json.dumps(names)}, 200
获取数据的JS
const [botnames, setBotsNames] = useState([]);
if(savedStrats.length==0){
fetch('/auth/fetch_bots_names', {method: 'GET'})
.then(res => {return res.text()}).then(response => {
try {
let r = JSON.parse(response);
setBotsNames(r['data']);
} catch {
console.log(response);
}
});
}
正如我指出的那样,botnames 值是一个类似于示例的字符串,但我需要它作为一个数组(我认为是一个 JS 数组?)以便制作一个包含列表元素的下拉菜单,谢谢提前
您可以使用 jsonify 将数据转换为 JSON 格式并在响应中发送。
您可以使用关键字参数或传递字典。
documentation 清楚地解释了用法。
from flask import jsonify
@bp.route('/fetch_bots_names', methods=['GET'])
def fetch_bots_names():
bot_names = [bot.name for bot in Bot.query.all()]
return jsonify({
'ok': True,
'msg':'Success',
'data': bot_names
})
在 React 中,您可以像这样使用 Fetch Api。
fetch('/auth/fetch_bots_names')
.then(resp => resp.json())
.then(data => {
setBotsNames(data.data);
});
我还没有测试代码,但它应该可以工作。
如果您想发送更大的数据集,您可能需要查看 Flask-Marshmallow。
这是一个结合使用 Flask-Marshmallow 和 marshmallow-sqlalchemy.
from flask import Flask
from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(__name__)
db = SQLAlchemy(app)
ma = Marshmallow(app)
class Bot(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
class BotSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Bot
with app.app_context():
db.drop_all()
db.create_all()
bots = [Bot(name=f'bot-{i+1}') for i in range(5)]
db.session.add_all(bots)
db.session.commit()
@app.route('/bots')
def bots():
bots = Bot.query.all()
bot_schema = BotSchema(many=True)
bot_data = bot_schema.dump(bots)
return jsonify(data=bot_data)
查询结果如下所示。
{
"data": [
{
"id": 1,
"name": "name-1"
},
{
"id": 2,
"name": "name-2"
},
{
"id": 3,
"name": "name-3"
},
{
"id": 4,
"name": "name-4"
}
]
}