-
Notifications
You must be signed in to change notification settings - Fork 4
feat: Adding support for Starlette Request and Responses #104
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
recursive-include azure *.py *.pyi | ||
recursive-include tests *.py | ||
include LICENSE README.md |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -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) | ||||||
|
||||||
Comment on lines
+8
to
+9
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is a typo in the URL ('hhttps'); it should be corrected to 'https'.
Suggested change
Copilot uses AI. Check for mistakes. Positive FeedbackNegative Feedback |
||||||
|
||||||
## 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 [[email protected]](mailto:[email protected]) with any additional questions or comments. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
__path__ = __import__("pkgutil").extend_path(__path__, __name__) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
__path__ = __import__("pkgutil").extend_path(__path__, __name__) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
__path__ = __import__("pkgutil").extend_path(__path__, __name__) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
__path__ = __import__("pkgutil").extend_path(__path__, __name__) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please remove this |
||
|
||
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" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Version can be |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
[build-system] | ||
requires = ["setuptools >= 61.0", "wheel"] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is wheel also needed here? |
||
build-backend = "setuptools.build_meta" | ||
|
||
[project] | ||
name = "azurefunctions-extensions-http-starlette" | ||
dynamic = ["version"] | ||
requires-python = ">=3.10" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. FastAPI supports 3.8+. Is there a reason starlette has to be 3.10+? |
||
authors = [{ name = "Azure Functions team at Microsoft Corp.", email = "[email protected]"}] | ||
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', | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can |
||
'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' | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you also add |
||
] | ||
|
||
[tool.setuptools.dynamic] | ||
version = {attr = "azurefunctions.extensions.http.starlette.__version__"} | ||
|
||
[tool.setuptools.packages.find] | ||
exclude = [ | ||
'azurefunctions.extensions.http','azurefunctions.extensions', | ||
'azurefunctions', 'tests', 'samples' | ||
] | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
# Copyright (c) Microsoft Corporation. All rights reserved. | ||
# Licensed under the MIT License. | ||
|
||
"""Bootstrap for '$ python setup.py test' command.""" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This line is legacy from using setup.py -- it can be removed |
||
|
||
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()) |
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please update the FastApi references to Starlette as well as any other Starlette specific README changes