Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
Using generator.send() while using stream_with_context in flask

Use case : an application which loads the user's music library. A loading bar is shown on the frontend. The proportion of library loaded is constantly returned to the frontend using a generator function and the **yield** keyword (this generator is returned as a response using **stream\_with\_context**). The frontend queries the flask view using a javascript **EventSource** object.

I want to give an option for the user to stop loading the library by clicking a button (and work with a subset of his/her library).

**Code:**

@app.route("/progress", methods=['GET'])
def progress():
gen = get_user_saved_tracks()
return Response(stream_with_context(gen), mimetype= 'text/event-stream')

def get_user_saved_tracks():
for i in range(numtracks):
#load track
yield "data:" + str((float(i+1)/(numtracks))*100) + "\n\n"
yield "data:" + "close" + "\n\n"

**Proposed approach:**

On clicking the button to stop loading the library, a generator.send() signal is sent to the get\_user\_saved\_tracks function.

def get_user_saved_tracks():
for i in range(numtracks):
foo = yield
if foo=='close':
return
#load track
yield "data:" + str((float(i+1)/(numtracks))*100) + "\n\n"
yield "data:" + "close" + "\n\n"

However, I'm not sure where to make the **gen.send()** call, since I'm using **stream\_with\_context**. Any help would be appreciated. I have a hunch that this approach might not work. I have also tried sending a flask [signal](http://flask.pocoo.org/docs/1.0/signals/) when the user clicks on "stop loading" to the generator, but that did not work (I can tell more about this approach if required).

/r/flask
https://redd.it/8z9k76
Appending data to a CSV file within a flask app

Hi! As seen in the title, I can't seem to add/append data or text to the csv that I have uploaded to my flask app that is being deployed in Google Cloud Run. But when I try it locally using Jupyter Notebook, it seems to work just fine. 

Here is the code:

#load the csv
features = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
url_data = pd.read_csv("RetrainDatabase.csv",low_memory=False)

#append the new data features
url_data.loc[len(url_data )] = features

#save the new csv
url_data.to_csv("RetrainDatabase_V2.csv", index=False)

/r/flask
https://redd.it/13fcehr