我正在使用一個由前同事撰寫的 resful api,當我使用 GET 將 json 從燒瓶 api 發送到前端,然后呼叫 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 陣列?),以便在串列的元素中制作一個下拉選單,在此先感謝
uj5u.com熱心網友回復:
您可以使用 jsonify 將資料轉換為 JSON 格式并在回應中發送。
您可以使用關鍵字引數或傳遞字典。檔案
清楚
地解釋了用法。
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"
}
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/428776.html
標籤:javascript Python 反应 烧瓶
