How can I update my Python app so my Flask function sends information to JavaScript without breaking the loop?

28 Views Asked by At

I am new to Flask and JavaScript, so help would be appreciated. I am making a mock draft simulator, and I have a function that contains a for loop, that simulates a selection for each team, adds the pick to a dictionary, and after the loop breaks, the dictionary is sent to JavaScript.

@app.route('/simulate-draft' , methods=['POST'])
def simulate_draft():
        # Get info from user and send to JavaScript
   for pick,info in draft_results.items():
        if team == user_team:
            #get pick from user
            #append to draft_results
        else:
            #simulate pick
            #append to draft_results
    return jsonify(draft_results)

However, I want the selections to be sent to JavaScript one by one, so the team the user chose to select for can make their selection, instead of the whole dictionary being sent at the end of the function I have read that yield could be a potential solution for this, but I keep getting errors when implementing this.

1

There are 1 best solutions below

0
Govind Kumar On

You can not send multiple responses for one single HTTP request. However, you can achieve this by using web sockets or sending a stream of data. In frontend you will need to process this stream.

 def simulate_draft():
    def generate_picks():
        for pick, info in draft_results.items():
            if team == user_team:
                yield f"data: {jsonify({pick: info})}\n\n"
            else:
                yield f"data: {jsonify({pick: info})}\n\n"

    return Response(generate_picks(), content_type='text/event-stream')