Create a Simple Music Streaming App with Flask
pypix.com
pypix.com
1) You cannot know the whole response at the time of the request (e.g. streaming news updates). 2) It's computationally expensive to calculate the whole response, and you don't want to make the user wait and/or calculate something that ends up not being used (e.g. if the user cancels the request). 3) You want to save bandwidth. If I were streaming music to you, and allowed you to switch tracks whenever you wanted, then I might not want your browser to start downloading the entire track (faster-than-real-time) when you click play. If I did, and you only listen to half-songs, then I would use twice as much bandwidth. I could release in shorter chunks and put a sleep or something before the yield in the generator function.
The content in this example is not streamed.
>> It’s the best practice to use a package instead of a
>> module for larger applications in Flask instead of a
>> single python file.
For something as small as this, i'd stay 1 single file. Keep it simple.If the app gets bigger, at the point where 1 file is becoming painful (and not before) it's trivial to refactor to a module. If you're a single person team, that point may be wayyy further down the line than you'd think.
Keep it simple as possible, you're safe knowing that it's trivial to grow -> module -> blueprints and so on.
Or, you can look at psobot's implementation of a streaming music app in forever.fm (http://blog.petersobot.com/introducing-forever-fm). The short version of it is that he uses a Python generator to generate frames, passes them through LAME, and then has Tornado hand out the music one frame at a time.
We made this mistake at a hackathon. Everything worked fine on dev machines, with the unsafe webserver built into flask.
When we tried to move it to a real server with wsgi, it stopped working. Users shouldn't have write access to the folder your code is in, and by default, they won't!