Python flask.stream_with_context() Examples

The following are 30 code examples of flask.stream_with_context(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: query.py    From marvin with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def _compressed_response(compression, results):
    ''' Compress the data before sending it back in the Response

    Parameters:
        compression (str):
            The compression type.  Either `json` or `msgpack`.
        results (dict):
            The current response dictionary

    Returns:
        A Flask Response object with the compressed data
    '''

    # pack the data
    mimetype = 'json' if compression == 'json' else 'octet-stream'
    try:
        packed = compress_data(results, compress_with=compression)
    except Exception as e:
        results['error'] = str(e)
        results['traceback'] = get_traceback(asstring=True)

    return Response(stream_with_context(packed), mimetype='application/{0}'.format(mimetype)) 
Example #2
Source File: __init__.py    From build-relengapi with Mozilla Public License 2.0 6 votes vote down vote up
def proxy_api(path):

    if path.startswith('details/'):
        tree = path[len('details/'):]
        log.info('Redirecting to tree: %s.' % tree)
        return flask.redirect('%s/show/%s' % (URL, tree))

    log.info('Proxying treestatus path: ' + path)

    # fetch the url, and stream it back
    response = requests.get(
        API_URL + path,
        stream=True,
        params=flask.request.args,
    )

    # reply with reponse from requests library
    log.info('Received treestatus response with status code %s' % (response.status_code))  # no-qa
    return flask.Response(
        response=flask.stream_with_context(response.iter_content()),
        status=response.status_code,
        headers=response.raw.headers.items(),
        content_type=response.headers['content-type'],
    ) 
Example #3
Source File: query.py    From marvin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def stream(self, args):
        ''' test query generator stream '''

        searchfilter = args.pop('searchfilter', None)
        compression = args.pop('compression', config.compression)
        mimetype = 'json' if compression == 'json' else 'octet-stream'

        release = args.pop('release', None)
        args['return_params'] = args.pop('returnparams', None)
        args['return_type'] = args.pop('rettype', None)
        q = Query(search_filter=searchfilter, release=release, **args)

        output = dict(data=None, chunk=q.limit, query=q.show(),
                      filter=searchfilter, params=q.params, returnparams=q.return_params, runtime=None,
                      queryparams_order=q._query_params_order, count=None, totalcount=None)

        return Response(stream_with_context(gen(q.query, compression=compression, params=q.params)), mimetype='application/{0}'.format(mimetype)) 
Example #4
Source File: run.py    From cloud-asr with Apache License 2.0 6 votes vote down vote up
def recognize_batch():
    data = {
        "model": request.args.get("lang", "en-GB"),
        "lm": request.args.get("lm", "default"),
        "wav": request.data
    }

    def generate(response):
        for result in response:
            yield json.dumps(result)

    try:
        worker = create_frontend_worker(os.environ['MASTER_ADDR'])
        response = worker.recognize_batch(data, request.headers)
        worker.close()

        return Response(stream_with_context(generate(response)))
    except MissingHeaderError:
        return jsonify({"status": "error", "message": "Missing header Content-Type"}), 400
    except NoWorkerAvailableError:
        return jsonify({"status": "error", "message": "No worker available"}), 503
    finally:
        worker.close() 
Example #5
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(generate()))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #6
Source File: proxy.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def proxy(url):
    req = _get_requests_session().get(url)
    return Response(stream_with_context(req.iter_content()),
                    content_type=req.headers['content-type']) 
Example #7
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(generate()))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #8
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context_as_decorator(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.stream_with_context
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(generate())
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #9
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context_and_custom_close(self):
        app = flask.Flask(__name__)
        app.testing = True
        called = []
        class Wrapper(object):
            def __init__(self, gen):
                self._gen = gen
            def __iter__(self):
                return self
            def close(self):
                called.append(42)
            def __next__(self):
                return next(self._gen)
            next = __next__
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(
                Wrapper(generate())))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!')
        self.assertEqual(called, [42]) 
Example #10
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(generate()))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #11
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context_as_decorator(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.stream_with_context
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(generate())
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #12
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(generate()))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #13
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context_as_decorator(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.stream_with_context
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(generate())
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #14
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context_and_custom_close(self):
        app = flask.Flask(__name__)
        app.testing = True
        called = []
        class Wrapper(object):
            def __init__(self, gen):
                self._gen = gen
            def __iter__(self):
                return self
            def close(self):
                called.append(42)
            def __next__(self):
                return next(self._gen)
            next = __next__
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(
                Wrapper(generate())))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!')
        self.assertEqual(called, [42]) 
Example #15
Source File: helpers.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_streaming_with_context(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(generate()))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #16
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context_as_decorator(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.stream_with_context
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(generate())
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #17
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(generate()))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #18
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context_as_decorator(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.stream_with_context
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(generate())
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #19
Source File: helpers.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_streaming_with_context_and_custom_close(self):
        app = flask.Flask(__name__)
        app.testing = True
        called = []
        class Wrapper(object):
            def __init__(self, gen):
                self._gen = gen
            def __iter__(self):
                return self
            def close(self):
                called.append(42)
            def __next__(self):
                return next(self._gen)
            next = __next__
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(
                Wrapper(generate())))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!')
        self.assertEqual(called, [42]) 
Example #20
Source File: APIUtils.py    From BiliBiliHelper with GNU General Public License v3.0 5 votes vote down vote up
def handle_route_logs(self, request):
        if request.method == "GET":
            return Response(stream_with_context(self.get_log()), content_type='application/json')
        elif request.method == "DELETE":
            return self.delete_logs()

    # /gift 
Example #21
Source File: helpers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_streaming_with_context(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(generate()))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #22
Source File: helpers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_streaming_with_context_as_decorator(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.stream_with_context
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(generate())
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #23
Source File: helpers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_streaming_with_context_and_custom_close(self):
        app = flask.Flask(__name__)
        app.testing = True
        called = []
        class Wrapper(object):
            def __init__(self, gen):
                self._gen = gen
            def __iter__(self):
                return self
            def close(self):
                called.append(42)
            def __next__(self):
                return next(self._gen)
            next = __next__
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(
                Wrapper(generate())))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!')
        self.assertEqual(called, [42]) 
Example #24
Source File: helpers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_streaming_with_context(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(flask.stream_with_context(generate()))
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #25
Source File: helpers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_streaming_with_context_as_decorator(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.stream_with_context
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(generate())
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #26
Source File: helpers.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_streaming_with_context_as_decorator(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.stream_with_context
            def generate():
                yield 'Hello '
                yield flask.request.args['name']
                yield '!'
            return flask.Response(generate())
        c = app.test_client()
        rv = c.get('/?name=World')
        self.assertEqual(rv.data, b'Hello World!') 
Example #27
Source File: api.py    From lyrebird-api-coverage with MIT License 5 votes vote down vote up
def get_coverage():
    return Response(stream_with_context(generate(app_context.coverage)), content_type='application/json')

# 保存测试数据在本地
#  /saveResult 
Example #28
Source File: gdriveutils.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def do_gdrive_download(df, headers):
    total_size = int(df.metadata.get('fileSize'))
    download_url = df.metadata.get('downloadUrl')
    s = partial(total_size, 1024 * 1024)  # I'm downloading BIG files, so 100M chunk size is fine for me

    def stream():
        for byte in s:
            headers = {"Range": 'bytes=%s-%s' % (byte[0], byte[1])}
            resp, content = df.auth.Get_Http_Object().request(download_url, headers=headers)
            if resp.status == 206:
                yield content
            else:
                log.warning('An error occurred: %s', resp)
                return
    return Response(stream_with_context(stream()), headers=headers) 
Example #29
Source File: test_flask.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_does_not_leak_scope(sentry_init, capture_events, app):
    sentry_init(integrations=[flask_sentry.FlaskIntegration()])
    events = capture_events()

    with configure_scope() as scope:
        scope.set_tag("request_data", False)

    @app.route("/")
    def index():
        with configure_scope() as scope:
            scope.set_tag("request_data", True)

        def generate():
            for row in range(1000):
                with configure_scope() as scope:
                    assert scope._tags["request_data"]

                yield str(row) + "\n"

        return Response(stream_with_context(generate()), mimetype="text/csv")

    client = app.test_client()
    response = client.get("/")
    assert response.data.decode() == "".join(str(row) + "\n" for row in range(1000))
    assert not events

    with configure_scope() as scope:
        assert not scope._tags["request_data"] 
Example #30
Source File: run.py    From cloud-asr with Apache License 2.0 5 votes vote down vote up
def crowdflower_export(model):
    def generate():
        yield "url\n"
        for row in recordings_model.get_random_recordings(model):
            yield "%s\n" % row.url

    return Response(stream_with_context(generate()), mimetype='text/csv')