|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import time |
| 16 | +import asyncio |
| 17 | +import functions_framework |
| 18 | +import functions_framework.aio |
| 19 | +from starlette.responses import StreamingResponse |
| 20 | + |
| 21 | +# Helper function for the synchronous streaming example. |
| 22 | +def slow_numbers(minimum, maximum): |
| 23 | + yield '<html><body><ul>' |
| 24 | + for number in range(minimum, maximum + 1): |
| 25 | + yield '<li>%d</li>' % number |
| 26 | + time.sleep(0.5) |
| 27 | + yield '</ul></body></html>' |
| 28 | + |
| 29 | +@functions_framework.http |
| 30 | +def hello_stream(request): |
| 31 | + """ |
| 32 | + A synchronous HTTP function that streams a response. |
| 33 | + Args: |
| 34 | + request (flask.Request): The request object. |
| 35 | + Returns: |
| 36 | + A generator, which will be streamed as the response. |
| 37 | + """ |
| 38 | + generator = slow_numbers(1, 10) |
| 39 | + return generator, {'Content-Type': 'text/html'} |
| 40 | + |
| 41 | +# Helper function for the asynchronous streaming example. |
| 42 | +async def slow_numbers_async(minimum, maximum): |
| 43 | + yield '<html><body><ul>' |
| 44 | + for number in range(minimum, maximum + 1): |
| 45 | + yield '<li>%d</li>' % number |
| 46 | + await asyncio.sleep(0.5) |
| 47 | + yield '</ul></body></html>' |
| 48 | + |
| 49 | +@functions_framework.aio.http |
| 50 | +async def hello_stream_async(request): |
| 51 | + """ |
| 52 | + An asynchronous HTTP function that streams a response. |
| 53 | + Args: |
| 54 | + request (starlette.requests.Request): The request object. |
| 55 | + Returns: |
| 56 | + A starlette.responses.StreamingResponse. |
| 57 | + """ |
| 58 | + generator = slow_numbers_async(1, 10) |
| 59 | + return StreamingResponse(generator, media_type='text/html') |
0 commit comments