diff --git a/azurefunctions-extensions-http-starlette/CHANGELOG.md b/azurefunctions-extensions-http-starlette/CHANGELOG.md new file mode 100644 index 0000000..e69de29 diff --git a/azurefunctions-extensions-http-starlette/LICENSE b/azurefunctions-extensions-http-starlette/LICENSE new file mode 100644 index 0000000..63447fd --- /dev/null +++ b/azurefunctions-extensions-http-starlette/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/azurefunctions-extensions-http-starlette/MANIFEST.in b/azurefunctions-extensions-http-starlette/MANIFEST.in new file mode 100644 index 0000000..e1ae5ad --- /dev/null +++ b/azurefunctions-extensions-http-starlette/MANIFEST.in @@ -0,0 +1,3 @@ +recursive-include azure *.py *.pyi +recursive-include tests *.py +include LICENSE README.md \ No newline at end of file diff --git a/azurefunctions-extensions-http-starlette/README.md b/azurefunctions-extensions-http-starlette/README.md new file mode 100644 index 0000000..1a02b74 --- /dev/null +++ b/azurefunctions-extensions-http-starlette/README.md @@ -0,0 +1,74 @@ +# Azure Functions Extensions Http FastApi library for Python +This library contains HttpV2 extensions for FastApi Request/Response types to use in your function app code. + +[Source code](https://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-http-fastapi) +| [Package (PyPi)](https://pypi.org/project/azurefunctions-extensions-http-fastapi/) +| API reference documentation +| Product documentation +| [Samples](hhttps://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-http-fastapi/samples) + + +## Getting started + +### Prerequisites +* Python 3.8 or later is required to use this package. For more details, please read our page on [Python Functions version support policy](https://learn.microsoft.com/en-us/azure/azure-functions/functions-versions?tabs=isolated-process%2Cv4&pivots=programming-language-python#languages). + + +### Instructions +1. Follow the guide to [create an app](https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-cli-python?tabs=windows%2Cbash%2Cazure-cli%2Cbrowser). If you're testing the function locally, make sure to update to the latest version of Core Tools. +2. Ensure your app is using programming model v2 and contains a http trigger function. +3. Add ```azurefunctions-extensions-http-fastapi``` to your requirements.txt +4. Import Request and different types of responses from ```azurefunctions.extensions.http.fastapi``` in your HttpTrigger functions. +5. Change the request and response types to ones imported from ```azurefunctions.extensions.http.fastapi```. +6. Add ```"PYTHON_ENABLE_INIT_INDEXING": "1"``` to your local.settings.json file or App Settings. +6. Run your function app and try it out! + +### Bind to the FastApi-type +The Azure Functions Extensions Http FastApi library for Python allows you to create a function app with FastApi Request or Response types. When your function runs, you will receive the request of FastApi Request type and you can return a FastApi response type instance. FastApi is one of top popular python web framework which provides elegant and powerful request/response types and functionalities to users. With this integration, you are empowered to use request/response the same way as using them in native FastApi. A good example is you can do http streaming upload and streaming download now! Feel free to check out [Fastapi doc](https://fastapi.tiangolo.com/reference/responses/?h=custom) for further reference. + +```python +# This Azure Function receives streaming data from a client and processes it in real-time. +# It demonstrates streaming upload capabilities for scenarios such as uploading large files, +# processing continuous data streams, or handling IoT device data. + +import azure.functions as func +from azurefunctions.extensions.http.starlette import Request, JSONResponse + +app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS) + + +@app.route(route="streaming_upload", methods=[func.HttpMethod.POST]) +async def streaming_upload(req: Request) -> JSONResponse: + """Handle streaming upload requests.""" + # Process each chunk of data as it arrives + async for chunk in req.stream(): + process_data_chunk(chunk) + + # Once all data is received, return a JSON response indicating successful processing + return JSONResponse({"status": "Data uploaded and processed successfully"}) + + +def process_data_chunk(chunk: bytes): + """Process each data chunk.""" + # Add custom processing logic here + pass +``` + +## Next steps + +### More sample code + +Get started with our [FastApi samples](hhttps://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-http-fastapi/samples). + +Several samples are available in this GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with FastApi: + +* [fastapi_samples_streaming_upload](https://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-http-fastapi/samples/fastapi_samples_streaming_upload) - An example on how to send and receiving a streaming request within your function. + +* [fastapi_samples_streaming_download](https://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-http-fastapi/samples/fastapi_samples_streaming_download) - An example on how to send your http response via streaming to the caller.t + +## Contributing +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/azurefunctions-extensions-http-starlette/azurefunctions/__init__.py b/azurefunctions-extensions-http-starlette/azurefunctions/__init__.py new file mode 100644 index 0000000..8db66d3 --- /dev/null +++ b/azurefunctions-extensions-http-starlette/azurefunctions/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/azurefunctions-extensions-http-starlette/azurefunctions/extensions/__init__.py b/azurefunctions-extensions-http-starlette/azurefunctions/extensions/__init__.py new file mode 100644 index 0000000..8db66d3 --- /dev/null +++ b/azurefunctions-extensions-http-starlette/azurefunctions/extensions/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/azurefunctions-extensions-http-starlette/azurefunctions/extensions/http/__init__.py b/azurefunctions-extensions-http-starlette/azurefunctions/extensions/http/__init__.py new file mode 100644 index 0000000..8db66d3 --- /dev/null +++ b/azurefunctions-extensions-http-starlette/azurefunctions/extensions/http/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/azurefunctions-extensions-http-starlette/azurefunctions/extensions/http/starlette/__init__.py b/azurefunctions-extensions-http-starlette/azurefunctions/extensions/http/starlette/__init__.py new file mode 100644 index 0000000..3e4b01e --- /dev/null +++ b/azurefunctions-extensions-http-starlette/azurefunctions/extensions/http/starlette/__init__.py @@ -0,0 +1,24 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) + +from starlette.requests import Request +from starlette.responses import (FileResponse, HTMLResponse, JSONResponse, + PlainTextResponse, RedirectResponse, Response, + StreamingResponse) + +from .web import RequestSynchronizer, WebApp, WebServer + +__all__ = [ + "WebServer", + "WebApp", + "Request", + "Response", + "RequestSynchronizer", + "StreamingResponse", + "HTMLResponse", + "PlainTextResponse", + "RedirectResponse", + "JSONResponse", + "FileResponse" +] + +__version__ = "0.0.1b1" diff --git a/azurefunctions-extensions-http-starlette/azurefunctions/extensions/http/starlette/web.py b/azurefunctions-extensions-http-starlette/azurefunctions/extensions/http/starlette/web.py new file mode 100644 index 0000000..e65ad4c --- /dev/null +++ b/azurefunctions-extensions-http-starlette/azurefunctions/extensions/http/starlette/web.py @@ -0,0 +1,141 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import logging +from typing import Callable + +import uvicorn +from azurefunctions.extensions.base import (RequestSynchronizer, + RequestTrackerMeta, ResponseLabels, + ResponseTrackerMeta, WebApp, + WebServer) +from pydantic import BaseModel +from starlette.applications import Starlette +from starlette.requests import Request as StarletteRequest +from starlette.responses import FileResponse as StarletteFileResponse +from starlette.responses import HTMLResponse as StarletteHTMLResponse +from starlette.responses import JSONResponse as StarletteJSONResponse +from starlette.responses import PlainTextResponse as StarlettePlainTextResponse +from starlette.responses import RedirectResponse as StarletteRedirectResponse +from starlette.responses import Response as StarletteResponse +from starlette.responses import StreamingResponse as StarletteStreamingResponse + + +class RequestSynchronizer(RequestSynchronizer): + def sync_route_params(self, request, path_params): + # add null checks for request and path_params + if request is None: + raise TypeError("Request object is None") + if path_params is None: + raise TypeError("Path parameters are None") + + request.path_params.clear() + request.path_params.update(path_params) + + +class Request(metaclass=RequestTrackerMeta): + request_type = StarletteRequest + synchronizer = RequestSynchronizer() + + +class Response(metaclass=ResponseTrackerMeta): + label = ResponseLabels.STANDARD + response_type = StarletteResponse + + +class StreamingResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.STREAMING + response_type = StarletteStreamingResponse + + +class HTMLResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.HTML + response_type = StarletteHTMLResponse + + +class PlainTextResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.PLAIN_TEXT + response_type = StarlettePlainTextResponse + + +class RedirectResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.REDIRECT + response_type = StarletteRedirectResponse + + +class JSONResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.JSON + response_type = StarletteJSONResponse + + +class FileResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.FILE + response_type = StarletteFileResponse + + +class StrResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.STR + response_type = str + + +class DictResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.DICT + response_type = dict + + +class BoolResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.BOOL + response_type = bool + + +class PydanticResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.PYDANTIC + response_type = BaseModel + + +class IntResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.INT + response_type = int + + +class FloatResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.FLOAT + response_type = float + + +class ListResponse(metaclass=ResponseTrackerMeta): + label = ResponseLabels.LIST + response_type = list + + +class WebApp(WebApp): + def __init__(self): + self.web_app = Starlette(debug=True) + + def route(self, func: Callable): + # Apply the api_route decorator + self.web_app.add_route(route=func, path="/{path:path}", methods=[ + "GET", + "POST", + "PUT", + "DELETE", + "OPTIONS", + "HEAD", + "PATCH", + "TRACE", + ]) + + def get_app(self): + return self.web_app + + +class WebServer(WebServer): + async def serve(self): + uvicorn_config = uvicorn.Config( + self.web_app, host=self.hostname, port=self.port, loop="asyncio", log_level="debug", lifespan="on", use_colors=True + ) + logging.info(f"Starting server on {self.hostname}:{self.port}") + # Create a Uvicorn server instance + server = uvicorn.Server(uvicorn_config) + + return await server.serve() diff --git a/azurefunctions-extensions-http-starlette/pyproject.toml b/azurefunctions-extensions-http-starlette/pyproject.toml new file mode 100644 index 0000000..368dffd --- /dev/null +++ b/azurefunctions-extensions-http-starlette/pyproject.toml @@ -0,0 +1,54 @@ +[build-system] +requires = ["setuptools >= 61.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "azurefunctions-extensions-http-starlette" +dynamic = ["version"] +requires-python = ">=3.10" +authors = [{ name = "Azure Functions team at Microsoft Corp.", email = "azurefunctions@microsoft.com"}] +description = "Starlette HTTP Python worker extension for Azure Functions." +readme = "README.md" +license = {text = "MIT License"} +classifiers= [ + 'License :: OSI Approved :: MIT License', + 'Intended Audience :: Developers', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Programming Language :: Python :: 3.12', + 'Programming Language :: Python :: 3.13', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: POSIX', + 'Operating System :: MacOS :: MacOS X', + 'Environment :: Web Environment', + 'Development Status :: 5 - Production/Stable', + ] +dependencies = [ + 'azurefunctions-extensions-base', + 'azure-functions', + 'starlette~=0.46.1', + 'uvicorn~=0.32.0', + 'pydantic~=2.10.0' + ] + +[project.optional-dependencies] +dev = [ + 'pytest', + 'pytest-cov', + 'coverage', + 'pytest-instafail', + 'pre-commit', + 'isort', + 'black' + ] + +[tool.setuptools.dynamic] +version = {attr = "azurefunctions.extensions.http.starlette.__version__"} + +[tool.setuptools.packages.find] +exclude = [ + 'azurefunctions.extensions.http','azurefunctions.extensions', + 'azurefunctions', 'tests', 'samples' + ] + diff --git a/azurefunctions-extensions-http-starlette/tests/__init__.py b/azurefunctions-extensions-http-starlette/tests/__init__.py new file mode 100644 index 0000000..528a01b --- /dev/null +++ b/azurefunctions-extensions-http-starlette/tests/__init__.py @@ -0,0 +1,20 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +"""Bootstrap for '$ python setup.py test' command.""" + +import os.path +import sys +import unittest +import unittest.runner + + +def suite(): + test_loader = unittest.TestLoader() + return test_loader.discover(os.path.dirname(__file__), pattern="test_*.py") + + +if __name__ == "__main__": + runner = unittest.runner.TextTestRunner() + result = runner.run(suite()) + sys.exit(not result.wasSuccessful()) diff --git a/azurefunctions-extensions-http-starlette/tests/test_web.py b/azurefunctions-extensions-http-starlette/tests/test_web.py new file mode 100644 index 0000000..01ae0c5 --- /dev/null +++ b/azurefunctions-extensions-http-starlette/tests/test_web.py @@ -0,0 +1,225 @@ +import asyncio +import unittest +from unittest.mock import MagicMock, patch + +from azurefunctions.extensions.base import (RequestTrackerMeta, ResponseLabels, + ResponseTrackerMeta) +from azurefunctions.extensions.http.starlette import ( + RequestSynchronizer, WebApp, WebServer) +from starlette.applications import Starlette +from starlette.requests import Request as StarletteRequest +from starlette.responses import FileResponse as StarletteFileResponse +from starlette.responses import HTMLResponse as StarletteHTMLResponse +from starlette.responses import JSONResponse as StarletteJSONResponse +from starlette.responses import PlainTextResponse as StarlettePlainTextResponse +from starlette.responses import RedirectResponse as StarletteRedirectResponse +from starlette.responses import Response as StarletteResponse +from starlette.responses import StreamingResponse as StarletteStreamingResponse + + +class TestRequestTrackerMeta(unittest.TestCase): + def test_request_type_defined(self): + class Request(metaclass=RequestTrackerMeta): + request_type = StarletteRequest + synchronizer = RequestSynchronizer() + + self.assertTrue(hasattr(Request, "request_type")) + self.assertEqual(Request.request_type, StarletteRequest) + + def test_request_type_undefined(self): + with self.assertRaises(Exception) as context: + + class Request(metaclass=RequestTrackerMeta): + pass + + self.assertTrue("Request type not provided" in str(context.exception)) + + +class TestResponseTrackerMeta(unittest.TestCase): + def test_response_labels_defined(self): + class Response(metaclass=ResponseTrackerMeta): + label = ResponseLabels.STANDARD + response_type = StarletteResponse + + self.assertTrue(hasattr(Response, "label")) + self.assertTrue(hasattr(Response, "response_type")) + self.assertEqual(Response.label, ResponseLabels.STANDARD) + self.assertEqual(Response.response_type, StarletteResponse) + + def test_response_labels_undefined(self): + with self.assertRaises(Exception) as context: + + class Response(metaclass=ResponseTrackerMeta): + pass + + self.assertTrue("Response label not provided" in str(context.exception)) + + def test_multiple_response_labels(self): + with self.assertRaises(Exception) as context: + + class Response1(metaclass=ResponseTrackerMeta): + label = ResponseLabels.STANDARD + response_type = StarletteResponse + + class Response2(metaclass=ResponseTrackerMeta): + label = ResponseLabels.STANDARD + response_type = StarletteJSONResponse + + self.assertTrue( + "Only one response type shall be recorded" in str(context.exception) + ) + + +class TestWebApp(unittest.TestCase): + def setUp(self): + self.web_app = WebApp() + + def test_route(self): + @self.web_app.route + def test_route(request: StarletteRequest): + return {"message": "Hello"} + + self.assertTrue( + "/{path:path}" + in [endpoint.path for endpoint in self.web_app.web_app.router.routes] + ) + route = [ + endpoint + for endpoint in self.web_app.web_app.router.routes + if endpoint.path == "/{path:path}" + ][0] + self.assertEqual( + route.methods, + {"GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"}, + ) + + def test_get_app(self): + self.assertIsInstance(self.web_app.get_app(), Starlette) + + +class TestWebServer(unittest.TestCase): + def setUp(self): + class TestApp: + pass + + self.test_app = TestApp() + self.web_app_mock = MagicMock().get_app() + self.web_app_mock.get_app.return_value = self.test_app + self.hostname = "localhost" + self.port = 8000 + self.web_server = WebServer(self.hostname, self.port, self.web_app_mock) + + @patch("uvicorn.Config") + @patch("uvicorn.Server") + def test_serve(self, server_mock, config_mock): + async def serve(): + await asyncio.sleep(0) + + config_instance_mock = config_mock.return_value + server_instance_mock = server_mock.return_value + server_instance_mock.serve = ( + serve # Mock the serve method to return a CoroutineMock + ) + + asyncio.get_event_loop().run_until_complete(self.web_server.serve()) + + config_mock.assert_called_once_with( + self.test_app, host=self.hostname, port=self.port + ) + server_mock.assert_called_once_with(config_instance_mock) + + async def run_serve(self): + await self.web_server.serve() + + +class TestRequestSynchronizer(unittest.TestCase): + def test_sync_route_params(self): + # Create a mock request object + mock_request = MagicMock() + + # Define some path parameters + path_params = {"param1": "value1", "param2": "value2"} + + # Create an instance of the ConcreteRequestSynchronizer + synchronizer = RequestSynchronizer() + + # Call the sync_route_params method with the mock request and path parameters + synchronizer.sync_route_params(mock_request, path_params) + + # Assert that the request's path_params have been updated with the provided path parameters + mock_request.path_params.clear.assert_called_once() + mock_request.path_params.update.assert_called_once_with(path_params) + + def test_sync_route_params_missing_request(self): + # Create an instance of the ConcreteRequestSynchronizer + synchronizer = RequestSynchronizer() + + # Define some path parameters + path_params = {"param1": "value1", "param2": "value2"} + + # Call the sync_route_params method with a None request and path parameters + with self.assertRaises(TypeError): + synchronizer.sync_route_params(None, path_params) + + def test_sync_route_params_missing_path_params(self): + # Create a mock request object + mock_request = MagicMock() + + # Create an instance of the ConcreteRequestSynchronizer + synchronizer = RequestSynchronizer() + + # Call the sync_route_params method with the mock request and None path parameters + with self.assertRaises(TypeError): + synchronizer.sync_route_params(mock_request, None) + + +class TestExtensionClasses(unittest.TestCase): + def test_request(self): + from azurefunctions.extensions.http.starlette.web import Request + + self.assertEqual(RequestTrackerMeta.get_request_type(), Request) + self.assertTrue( + isinstance(RequestTrackerMeta.get_synchronizer(), RequestSynchronizer) + ) + + def test_response(self): + self.assertEqual( + ResponseTrackerMeta.get_response_type(ResponseLabels.STANDARD), + StarletteResponse, + ) + + def test_streaming_response(self): + self.assertEqual( + ResponseTrackerMeta.get_response_type(ResponseLabels.STREAMING), + StarletteStreamingResponse, + ) + + def test_html_response(self): + self.assertEqual( + ResponseTrackerMeta.get_response_type(ResponseLabels.HTML), + StarletteHTMLResponse, + ) + + def test_plain_text_response(self): + self.assertEqual( + ResponseTrackerMeta.get_response_type(ResponseLabels.PLAIN_TEXT), + StarlettePlainTextResponse, + ) + + def test_redirect_response(self): + self.assertEqual( + ResponseTrackerMeta.get_response_type(ResponseLabels.REDIRECT), + StarletteRedirectResponse, + ) + + def test_json_response(self): + self.assertEqual( + ResponseTrackerMeta.get_response_type(ResponseLabels.JSON), + StarletteJSONResponse, + ) + + def test_file_response(self): + self.assertEqual( + ResponseTrackerMeta.get_response_type(ResponseLabels.FILE), + StarletteFileResponse, + )