3

I have a scenario where I want to show output of a long running script through a Flask API. I followed an example given for Flask and it works. I get dmesg steam in my browser.

import subprocess
import time
from flask import Flask, Response

app = Flask(__name__)

@app.route('/yield')
def index():
    def inner():
        proc = subprocess.Popen(
            ['dmesg'],  # call something with a lot of output so we can see it
            shell=True,
            stdout=subprocess.PIPE
        )

        for line in iter(proc.stdout.readline,''):
            time.sleep(1)  # Don't need this just shows the text streaming
            yield line.rstrip() + '<br/>\n'

    return Response(inner(), mimetype='text/html')  # text/html is required for most browsers to show this

The thing is, I have been using Flask-Restful from a long time. So I want to do the streaming using it. I tried it and it's not working.

import subprocess
import time
from flask import Response
from flask_restful import Resource

class CatalogStrings(Resource):

    def get(self):
        return Response(inner(), mimetype='text/html')

def inner():
    proc = subprocess.Popen(
        ['dmesg'],  # call something with a lot of output so we can see it
        shell=True,
        stdout=subprocess.PIPE
    )

    for line in iter(proc.stdout.readline, ''):
        time.sleep(1)  # Don't need this just shows the text streaming
        yield line.rstrip() + '<br/>\n'

Please help

Hussain
  • 5,057
  • 6
  • 45
  • 71

0 Answers0