示例#1
0
async def handler(request):
    async def streaming(response):
        while True:
            body = await request.stream.get()
            if body is None:
                break
            body = body.decode('utf-8').replace('1', 'A')
            await response.write(body)
    return stream(streaming)
示例#2
0
    async def put(request):
        assert isinstance(request.stream, asyncio.Queue)

        async def streaming(response):
            while True:
                body = await request.stream.get()
                if body is None:
                    break
                response.write(body.decode('utf-8'))
        return stream(streaming)
示例#3
0
    async def put(request):
        assert isinstance(request.stream, StreamBuffer)

        async def streaming(response):
            while True:
                body = await request.stream.read()
                if body is None:
                    break
                await response.write(body.decode("utf-8"))

        return stream(streaming)
示例#4
0
    async def post(request, id):
        assert isinstance(request.stream, asyncio.Queue)

        async def streaming(response):
            while True:
                body = await request.stream.get()
                if body is None:
                    break
                await response.write(body.decode("utf-8"))

        await asyncio.sleep(1.0)
        # at this point client is already disconnected
        app.still_serving_cancelled_request = True

        return stream(streaming)
示例#5
0
 async def test(request):
     response = stream(sample_streaming_fn, content_type="text/csv")
     response.cookies["test"] = "modified"
     response.cookies["test"] = "pass"
     return response
示例#6
0
 async def test(request):
     return stream(sample_streaming_fn, content_type='text/csv')
示例#7
0
    async def as_csv(self, request, name, hash, **kwargs):
        stream = request.args.get("_stream")
        if stream:
            # Some quick sanity checks
            if not self.ds.config["allow_csv_stream"]:
                raise DatasetteError("CSV streaming is disabled", status=400)
            if request.args.get("_next"):
                raise DatasetteError(
                    "_next not allowed for CSV streaming", status=400
                )
            kwargs["_size"] = "max"
        # Fetch the first page
        try:
            response_or_template_contexts = await self.data(
                request, name, hash, **kwargs
            )
            if isinstance(response_or_template_contexts, response.HTTPResponse):
                return response_or_template_contexts
            else:
                data, extra_template_data, templates = response_or_template_contexts
        except (sqlite3.OperationalError, InvalidSql) as e:
            raise DatasetteError(str(e), title="Invalid SQL", status=400)

        except (sqlite3.OperationalError) as e:
            raise DatasetteError(str(e))

        except DatasetteError:
            raise

        # Convert rows and columns to CSV
        headings = data["columns"]
        # if there are expanded_columns we need to add additional headings
        expanded_columns = set(data.get("expanded_columns") or [])
        if expanded_columns:
            headings = []
            for column in data["columns"]:
                headings.append(column)
                if column in expanded_columns:
                    headings.append("{}_label".format(column))

        async def stream_fn(r):
            nonlocal data
            writer = csv.writer(LimitedWriter(r, self.ds.config["max_csv_mb"]))
            first = True
            next = None
            while first or (next and stream):
                try:
                    if next:
                        kwargs["_next"] = next
                    if not first:
                        data, extra_template_data, templates = await self.data(
                            request, name, hash, **kwargs
                        )
                    if first:
                        writer.writerow(headings)
                        first = False
                    next = data.get("next")
                    for row in data["rows"]:
                        if not expanded_columns:
                            # Simple path
                            writer.writerow(row)
                        else:
                            # Look for {"value": "label": } dicts and expand
                            new_row = []
                            for cell in row:
                                if isinstance(cell, dict):
                                    new_row.append(cell["value"])
                                    new_row.append(cell["label"])
                                else:
                                    new_row.append(cell)
                            writer.writerow(new_row)
                except Exception as e:
                    print('caught this', e)
                    r.write(str(e))
                    return

        content_type = "text/plain; charset=utf-8"
        headers = {}
        if self.ds.cors:
            headers["Access-Control-Allow-Origin"] = "*"
        if request.args.get("_dl", None):
            content_type = "text/csv; charset=utf-8"
            disposition = 'attachment; filename="{}.csv"'.format(
                kwargs.get('table', name)
            )
            headers["Content-Disposition"] = disposition

        return response.stream(
            stream_fn,
            headers=headers,
            content_type=content_type
        )
async def streaming(request):
    async def streaming_fn(response):
        response.write('foo')
        response.write('bar')
    return stream(streaming_fn)
示例#9
0
 async def async_handler_exception(request, exception):
     return stream(
         sample_streaming_fn,
         content_type="text/csv",
     )
示例#10
0
async def camera_stream(request):
    camera = Camera(320, 240, 10)
    # camera = Camera()
    return response.stream(
        camera.stream,
        content_type='multipart/x-mixed-replace; boundary=frame')
示例#11
0
async def blueprint_route(request):
    async def streaming_fn(response):
        response.write("foo")

    return stream(streaming_fn)
示例#12
0
async def streaming(request):
    async def streaming_fn(response):
        response.write("foo")
        response.write("bar")

    return stream(streaming_fn)
示例#13
0
async def index(request):
    async def streaming_fn(response):
        response.write('foo')
        response.write('bar')
    return response.stream(streaming_fn, content_type='text/plain')
示例#14
0
 async def test(request):
     return stream(
         sample_streaming_fn,
         headers={"Content-Length": "7"},
         content_type="text/csv",
     )
示例#15
0
async def test(request):
    async def sample_streaming_fn(response):
        response.write('foo,')
        response.write('bar')

    return stream(sample_streaming_fn, content_type='text/csv')
示例#16
0
async def random_bytes(request, count):
    assert count >= 0
    return response.stream(
        send_bytes(count),
        content_type='application/octet-stream'
    )
示例#17
0
 async def test(request):
     return stream(sample_streaming_fn, content_type='text/csv')
示例#18
0
        async def receive(request: Request):
            ## extract required data
            print(request.form)
            sender_id = await self._extract_sender(request)
            input_channel = self._extract_platform(request)
            text = self._extract_message(request)

            attachment = self._extract_attachment(request)
            if attachment != None:
                text = attachment

            should_use_stream = rasa.utils.endpoints.bool_arg(request,
                                                              "stream",
                                                              default=False)

            ## sends message in to rasa core
            if should_use_stream:
                return response.stream(
                    self.stream_response(on_new_message, text, sender_id),
                    content_type="text/event-stream",
                )
            else:

                collector = CollectingOutputChannel()
                print('1st collector.message')
                print(collector.messages)
                print(type(collector.messages))
                # noinspection PyBroadException
                try:
                    await on_new_message(
                        UserMessage(text,
                                    collector,
                                    sender_id,
                                    input_channel=input_channel))

                    print('2nd after await onnewmessage collector.message')
                    print(collector.messages)
                    print(type(collector.messages))

                    message_received_is = collector.messages[0]
                    text = message_received_is.get("text")
                    print(text)
                    recipient_id = message_received_is.get("recipient_id")

                    message = {
                        "success":
                        1,
                        "message": [{
                            "message": {
                                "template": {
                                    "elements": {
                                        "title": text,
                                        "says": "",
                                        "visemes": ""
                                    }
                                }
                            }
                        }],
                        "session":
                        sender_id
                    }

                    #
                    # message = {
                    #     "success": 1,
                    #     "message": text,
                    #     "session": recipient_id
                    # }
                    print(
                        '#############printing message reply to talkk#################'
                    )
                    print(message)
                    return response.json(message)

                except CancelledError:
                    logger.error("Message handling timed out for "
                                 "user message '{}'.".format(text))
                except Exception:
                    logger.exception("An exception occured while handling "
                                     "user message '{}'.".format(text))
示例#19
0
async def view(request):
    return sanic_response.stream(
        identifier.stream,
        content_type='multipart/x-mixed-replace; boundary=frame')
示例#20
0
async def index(request):
    async def streaming_fn(response):
        await response.write('foo')
        await response.write('bar')
    return response.stream(streaming_fn, content_type='text/plain')
示例#21
0
    async def stream_response(request):
        async def sample_streaming_fn(response):
            await response.write("foo,")
            await response.write("bar")

        return stream(sample_streaming_fn, content_type="text/csv")