pythonpytube

view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list


TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.

from flask import Flask, jsonify, request
from pytube import YouTube
app = Flask(__name__)

@app.route('/youtube', methods=['POST'])
def hello_world():
    url = request.form['d_url']
    yt_video = YouTube(url)
    videos = yt_video.streams
    res_list = list(enumerate(videos))
    return res_list

if __name__ == "__main__":
    app.run(debug =True)

Solution

  • you cannot return a list directly from flask.view you have to convert it to json object.

    Apparently directly using jsonify from Flask did not as it could not serialize the Stream object in res_list. When doing jsonify(res_list) I got the following error:

    TypeError: Object of type Stream is not JSON serializable
    

    Using jsonpickle did the job. Below code is working:

    from flask import Flask, jsonify, request
    from pytube import YouTube
    import jsonpickle
    
    app = Flask(__name__)
    
    
    @app.route('/youtube', methods=['POST'])
    def hello_world():
        url = request.form['d_url'] #'http://youtube.com/watch?v=9bZkp7q19f0'
        yt_video = YouTube(url)
        videos = yt_video.streams
        res_list = list(enumerate(videos))
        return jsonpickle.encode(res_list)
    
    if __name__ == "__main__":
        app.run(debug =True)