flask (1)

Create a Simple Music Streaming App with Flask



The final product of this tutorial is a simple music streaming and downloading application.

In this application, the user will be able to do the following:

  • Upload music themselves and Play the music uploaded by the user
  • Download the music via HTTP and streaming it with HTML5 audio.

Introduction

flask1

hello

 

Let’s Get Started!

The first thing to do is to install Flask.  To do this, simply run the command

You can refer the official Flask documentation to install Flask correctly.

To verify whether Flask is installed correctly in your  system, go to the command prompt/Terminal and enter into Python shell and then type the command

If the command raises no error, then you are good to go.

Now open up your favorite text editor( we recommend Sublime Text 2) and create the main root folder and name it as musicstream  and then create a python package inside the root folder and name it as app .

Python package can be created by creating a new python file called __init__.py inside the folder to mark it as a python package.

Learn more about Python packages from the official Python docs.

Create another two folders static and templates inside the app directory and another folder inside static called uploads and css and one python file called run.py inside your root folder. Now your directory structure should look like this.

direc

It’s the best practice to use a package instead of a module for larger applications in Flask instead of a single python file.

Initializing the application

Now inside your __init__.py file add the following bunch of code.

So what did that code do?

We just imported the Flask class and then creating an instance of Flask class and created an object of it and If you are using a single module (as in this example), you should use __name__ with the class.

Next we have the UPLOAD_FOLDER this is where we will store the uploaded files and then in the final line we are configuring the app variable with our UPLOAD_FOLDER.

Save it and then create a new file inside the app package called as views.py this file will hold all our views.

Since our stubs are in place we can start developing the related code.

lets open views.py and then import some more methods

We have imported the app object from the app package along with some other imports.

Now add the index method

We have decorated the route for the index and when it’s called the index.html will be called but we haven’t yet created it, so lets create that first and then come back here.

In your templates directory, create layout.html file which will serve as the base template for our file and we will inherit from this base file.

It’s just the normal html , its self-explanatory, we are using inbuilt Flask method url_for to call the style-sheets from our static directory, url_for generates a URL to the given endpoint with the method provided.

Download Bootstrap and include only bootstrap.css file inside css folder along with custom.css as the other files are not needed for our application.
include this css into custom.css file

Now we have {% block content %} and {% end block%} these are jinja2 blocks, in jinja2 the decision-making stuffs are enclosed inside {% %} and the variables to display into the browser are enclosed into {{  }} . the purpose of the block tag does is to tell the template engine that a child template may override those portions of the template and that’s how we can achieve the inheritance in templates and we can have common portions of the entire site into one place without writing the code all over again in all the pages.

Next create index.html and inherit the layout.html and fill out the block contents like this

now, the h1 content will be the injected into the layout.html in the position where we have declared the block tags.

( You can verify this by seeing the source of the web page by pressing  ctrl + U )

Now in run.py include this lines of code

This is pretty simple and straightforward.

Now if you run this command

you will get an error because you havent yet linked the views with your app object, to do so include this line at the bottom in __init__.py.

Now run the app and you will get the pretty welcome message, it everything worked well, you will see something like this.

hello

 

Uploading Songs

For uploading file, we will create two route, one for uploading and the another for displaying the uploaded content.

Add this lines below the index method in view.py

lets see line by line, first we declared the route for upload and it accepts only GET and POST request to that method i.e you can only get and post on this url http://localhost:5000/upload and then we are checking if the method is post , get the file from the user and if it has a filename save it to our uploaded folder which we declared before else if the request is get, render the index.html template.

next method takes the filename of the file we uploaded as an argument and returns the file from the directory with the same filename to be rendered by the template to view in the browser. These methods are pretty straight forward too. isn’t it ?

Now we have our views in place lets modify our index.html to upload the file and stream the audio.

The code is plain html except the url_for tags in between, the url_for takes the method of the function to call as the argument and it renders the anchor tags for us.

We are using the single file to upload the file as well as to display the uploaded file.

Conclusion

With this we have completed our Mini Application using Flask.

For those of you who are Python experts, I’m sure that you can find a way to optimize this application even more. In addition, it would be great to share any optimizations that you make in the comments section so that readers can get even more out of this tutorial.


  • Raphael Marra

    Great tutorial.
    Flask is a amazing microframework.
    I’m seeing CherryPy. What are you think about?

    • ajkumar25

      I have been working with both for the past few months, using CherryPy as the server and Flask as the framework — and I have had no problems at all. Running Flask with the development server was not stable — running Flask with CherryPy as the server has been rock-solid.

      • Kousik Kumar

        You can configure flask with apache.

        • ajkumar25

          Yes we can configure flask with apache, but i prefer cherrypy.

  • Yaya

    Thanks for the starting point!

    Note: with current version of Flask (0.10) one need to modifiy the ‘upload’ route:

    @app.route(‘/uploads/’)
    def uploaded_file(filename):

    • ajkumar25

      The version used in this tutorial is 0.10

    • etng

      and we should change the template’s tag

      to

  • spilrdt

    I get this error when I try to upload a song.

    IOError: [Errno 2] No such file or directory: ‘./uploads/

    • ajkumar25

      Sorry for the late reply, i have updated the UPLOAD_FOLDER code. Have a look at it.

      • spilrdt

        Thanks for your reply, but it’s still not streaming..
        The error logs says:

        GET /uploads/..song..mp3 HTTP/1.1″ 404 -

        • ajkumar25

          Can you show the pastebin of your traceback.

          • spilrdt

            I don’t get a traceback. Just the entry in the log as I showed above. The upload goes fine, seems to be the player that just won’t work.

          • spilrdt

            any idea if it could be the player ?

          • ajkumar25

            HTML5 Audio has problems with browsers. Adobe Flask Player is needed to run the Audio in browser. check if its correctly installed.

          • Kerbobotat

            Im getting the same issue as spilrdt, file seems to upload fine, and then in sublimetext I’m getting this:

            127.0.0.1 – - [27/Nov/2013 19:44:42] “POST /upload HTTP/1.1″ 200 -
            127.0.0.1 – - [27/Nov/2013 19:44:42] “GET /uploads/hydrogen.mp3 HTTP/1.1″ 404 -

            checked the project folder, and it seems that it transferred the file properly, but it doesn’t seem to want to show/stream it at all.

          • ajkumar25

            Just checked again and it plays well in my browser.

          • ajkumar25

            My Traceback

            127.0.0.1 – - [28/Nov/2013 09:08:17] “GET /upload HTTP/1.1″ 200 -

            127.0.0.1 – - [28/Nov/2013 09:08:36] “POST /upload HTTP/1.1″ 200 -

            127.0.0.1 – - [28/Nov/2013 09:08:36] “GET /uploads/on_the_floor.mp3.mp3 HTTP/1.1″ 200 -

          • mapleray

            Hello, same issue, and I change @app.route(‘/uploads/’) to @app.route(‘/loads/’) all things get work!

        • BruceLi

          Change the route rule of method upload_file(filename) to ‘/uploads/’ works for me. Hope this helps.

  • Neeraj

    File “run.py”, line 1, in
    from app import app
    ImportError: No module named app

    I am getting this error on trying to run run.py. What could be the error?

    • ajkumar25

      Double check that app is a package ? Have you included the __init__.py file ?

      • Neeraj

        Thank you for replying.

        I had placed run.py in the wrong directory, and did not notice it until after I posted the above.

      • CSMajor

        I’ve checked __init__.py was in the app folder to make it a python package. But I still get the No module named app error. I’m going to recreate everything to see if I catch something, but any other suggestions?

    • Mayank Chaudhary

      It’s because sys.path doesn’t contain the path to ‘app’ package.
      Include this in run.py-
      import sys
      sys.path.insert(0,’path/to/directory’)
      Then it’ll work.

  • jerome

    Hi thx for this great tuto !!
    Is it possible to translate it and diffuse it ?
    (with credit, link… watever)

  • Tushar Rajput

    getting error after executing

    404 Not Found.

    Not Found

    The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
    What to do?

  • Shaun Koo

    Hi all I am unable to see the player in the browser even though I can upload and download fine..any suggestions?