简体   繁体   English

如何将列表从 flask 后端传递到 reactjs 前端?

[英]how to pass a list from flask backend to a reactjs frontend?

I am working whit a restful API, written by an ex-coworker, when I use a GET to send a json from the flask API to the frontend and then call the value in the json, I get a string instead an array, the list looks like this我正在使用由前同事编写的宁静 API,当我使用 GET 将 json 从 flask API 发送到前端,然后调用 json 中的值时,我得到一个字符串而不是数组,列表看起来像这样

['ETH/BTC','LTC/BTC','BNB/BTC'] ['ETH/BTC','LTC/BTC','BNB/BTC']

Here is what I think is relevant from the code这是我认为与代码相关的内容

The route:路线:

@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

The JS to fetch the data获取数据的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);
        }
      });
    }

and as I pointed, the botnames value is a string like the example, but I need it as an array(I think an JS array?) in order to make a drop menu whit the elements of the list, thanks in advance正如我指出的那样,botnames 值是一个类似于示例的字符串,但我需要它作为一个数组(我认为是一个 JS 数组?)以便制作一个包含列表元素的下拉菜单,在此先感谢

You can use jsonify to convert your data into JSON format and send it in a response.您可以使用 jsonify 将数据转换为 JSON 格式并在响应中发送。
You can either use keyword arguments or pass a dict.您可以使用关键字 arguments 或传递字典。
The documentation clearly explains the usage. 文档清楚地解释了用法。

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
    })

In React you use the Fetch Api like this.在 React 中,您可以像这样使用 Fetch Api。

fetch('/auth/fetch_bots_names')
  .then(resp => resp.json())
  .then(data => {
    setBotsNames(data.data);
  });

I haven't tested the code, but it should work.我还没有测试代码,但它应该可以工作。

You might want to take a look at Flask-Marshmallow if you want to send larger datasets.如果你想发送更大的数据集,你可能想看看Flask-Marshmallow
Here is a quick example using Flask-Marshmallow in combination with marshmallow-sqlalchemy.这是一个将 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)

The result of the query looks like this.查询结果如下所示。

{
  "data": [
    {
      "id": 1, 
      "name": "name-1"
    }, 
    {
      "id": 2, 
      "name": "name-2"
    }, 
    {
      "id": 3, 
      "name": "name-3"
    }, 
    {
      "id": 4, 
      "name": "name-4"
    }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将输入数据从 ReactJS 传递到 Flask-Python(后端) - How to pass input data from ReactJS to Flask-Python (Backend) 使用 axios 将 Json 数据从 ReactJs 前端发布到 Flask 后端 - Post Json data from ReactJs Frontend to Flask Backend with axios ReactJS作为前端和Flask作为后端之间的连接问题 - connection problem between ReactJS As Frontend And Flask As Backend 将 reactjs 前端与 python + flask 后端相结合 - combining reactjs frontend with python + flask backend 如何将唯一标识符从我的 express 后端服务器传递到我的前端 reactjs 以显示在我的 web 应用程序中? - How can I pass a unique identifier from my express backend server to my frontend reactjs to be displayed in my web application? 从前端发送.wav 文件到 Flask 后端 - Sending .wav file from frontend to Flask backend 在Flask应用中将变量从后端传递到前端 - Passing a variable from the backend to the frontend in a Flask app 如何将数据从AngularJS前端传递到Nodejs后端? - How to pass data from AngularJS frontend to Nodejs backend? 如何将数据从前端jQuery传递到后端node.js - How to pass data from frontend jQuery to backend node.js 如何使用 javascript(Reactjs) 作为前端和 node.js 作为后端创建依赖下拉列表 - How to create dependent dropdown list using javascript(Reactjs) as frontend and node.js as backend
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM