tonybaloney / ants-azure-demos Goto Github PK
View Code? Open in Web Editor NEWCollection of PoCs and Azure Demos
Collection of PoCs and Azure Demos
The /docs endpoint only seems to work for "anonymous" functions. Is there anything I can do to use it with authlevel "function"?
I was running the API for several months. I tried to update the API today and pushed the new code to Azure and ended up with http 500 error codes. Seems to be an error in the http_asgi.py if i am not mistaken. This is the error i got from the Application Insights.
The API is working locally in the virtual environment. But when i deploy it to Azure it stopped working.
Do you know what the problem might be?
Exception while executing function: Functions.my-appname <--- Result: Failure Exception: TypeError: '<' not supported between instances of 'NoneType' and 'int' Stack: File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 402, in _handle__invocation_request call_result = await self._loop.run_in_executor( File "/usr/local/lib/python3.9/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 611, in _run_sync_func return ExtensionManager.get_sync_invocation_wrapper(context, File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/extension.py", line 215, in _raw_invocation_wrapper result = function(**args) File "/home/site/wwwroot/my-appname/__init__.py", line 230, in main return AsgiMiddleware(app).handle(req, context) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure/functions/_http_asgi.py", line 146, in handle return self._handle(req, context) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure/functions/_http_asgi.py", line 152, in _handle asgi_response = self._loop.run_until_complete( File "/usr/local/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete return future.result() File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure/functions/_http_asgi.py", line 65, in from_app await app(scope, res._receive, res._send) File "/home/site/wwwroot/.python_packages/lib/site-packages/fastapi/applications.py", line 212, in __call__ await super().__call__(scope, receive, send) File "/home/site/wwwroot/.python_packages/lib/site-packages/starlette/applications.py", line 119, in __call__ await self.middleware_stack(scope, receive, send) File "/home/site/wwwroot/.python_packages/lib/site-packages/starlette/middleware/errors.py", line 181, in __call__ raise exc File "/home/site/wwwroot/.python_packages/lib/site-packages/starlette/middleware/errors.py", line 159, in __call__ await self.app(scope, receive, _send) File "/home/site/wwwroot/.python_packages/lib/site-packages/starlette/exceptions.py", line 87, in __call__ raise exc File "/home/site/wwwroot/.python_packages/lib/site-packages/starlette/exceptions.py", line 76, in __call__ await self.app(scope, receive, sender) File "/home/site/wwwroot/.python_packages/lib/site-packages/starlette/routing.py", line 659, in __call__ await route.handle(scope, receive, send) File "/home/site/wwwroot/.python_packages/lib/site-packages/starlette/routing.py", line 259, in handle await self.app(scope, receive, send) File "/home/site/wwwroot/.python_packages/lib/site-packages/starlette/routing.py", line 61, in app response = await func(request) File "/home/site/wwwroot/.python_packages/lib/site-packages/fastapi/routing.py", line 216, in app solved_result = await solve_dependencies( File "/home/site/wwwroot/.python_packages/lib/site-packages/fastapi/dependencies/utils.py", line 465, in solve_dependencies response = response or Response( File "/home/site/wwwroot/.python_packages/lib/site-packages/starlette/responses.py", line 50, in __init__ self.init_headers(headers) File "/home/site/wwwroot/.python_packages/lib/site-packages/starlette/responses.py", line 77, in init_headers and not (self.status_code < 200 or self.status_code in (204, 304))
I am trying to connect the FastAPI based Functions app to Azure File Storage through the Output bindings.
{
"name": "mntbl",
"type": "table",
"tableName": "maintable",
"partitionKey": "district_id",
"rowKey": "ri_id",
"connection": "AzureWebJobsStorage",
"direction": "out"
},
mntbl is the name of the binding and as per the docs I need to add it to the main function.
As it stands before:
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
return AsgiMiddleware(app).handle(req, context)
I can add it here by:
def main(req: func.HttpRequest, mntbl: func.Out[str], context: func.Context) -> func.HttpResponse:
return AsgiMiddleware(app).handle(req, mntbl, context)
But I guess I'll need to make appropriate changes in the http_asgi.py
file as well.
The relevant parts of that file are I suppose:
class AsgiMiddleware:
def __init__(self, app):
logging.debug("Instantiating ASGI middleware.")
self._app = app
self.loop = asyncio.new_event_loop()
logging.debug("asyncio event loop initialized.")
# Usage
# main = func.AsgiMiddleware(app).main
@property
def main(self) -> Callable[[HttpRequest, Context], HttpResponse]:
return self._handle
# Usage
# return func.AsgiMiddleware(app).handle(req, context)
def handle(
self, req: HttpRequest, context: Optional[Context] = None
) -> HttpResponse:
logging.info(f"Handling {req.url} as ASGI request.")
return self._handle(req, context)
def _handle(self, req: HttpRequest,
context: Optional[Context]) -> HttpResponse:
asgi_request = AsgiRequest(req, context)
asyncio.set_event_loop(self.loop)
scope = asgi_request.to_asgi_http_scope()
asgi_response = self.loop.run_until_complete(
AsgiResponse.from_app(self._app, scope, req.get_body())
)
return asgi_response.to_func_response()
But I am unsure how to handle it here? Any inputs?
The alternate would be to use the Tables SDK directly I suppose, but it would be useful to be able to use the functions binding as well as they take care of auth etc.
Hi, thanks for the repo, this helps a lot! Unfortunately, it seems like the FastAPI BackgroundTasks don't work as intended. The background task is executed successfully but the response is only sent AFTER the background task is finished. I copied the exact same code to a normal FastAPI app where the background task works as intended. Therefore, I think this is an issue. Can you confirm this or am I doing something wrong?
Hi
Thanks so much for this. Azure functions with the vscode extension make this whole thing child's play.
Do you or anyone know how I could use AsyncIOMotorClient
in the Azure functions runtime?
The following doesn't work
# main.py
from motor.motor_asyncio import AsyncIOMotorClient
async def start_mongo():
app.mongodb_client = AsyncIOMotorClient(settings.DB_URL)
app.mongodb = app.mongodb_client[settings.DB_NAME]
async def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
await start_mongo()
return AsgiMiddleware(app).handle(req, context)
I get
Functions:
ingest: [GET,POST,PUT,PATCH,DELETE] http://localhost:7071//{*route}
For detailed output, run func with --verbose flag.
[2021-08-24T17:28:43.732Z] Worker process started and initialized.
[2021-08-24T17:28:45.020Z] Executing 'Functions.ingest' (Reason='This function was programmatically called via the host APIs.', Id=2545ed75-d31e-4714-bda6-031cdf56ff7a)
[2021-08-24T17:28:46.300Z] /usr/lib/azure-functions-core-tools-3/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py:440: RuntimeWarning: coroutine 'AsgiResponse.from_app' was never awaited
[2021-08-24T17:28:46.300Z] Handling http://localhost:7071/authors?num_authors=1 as ASGI request.
[2021-08-24T17:28:46.300Z] return protos.StreamingMessage(
[2021-08-24T17:28:46.303Z] RuntimeWarning: Enable tracemalloc to get the object allocation traceback
[2021-08-24T17:28:46.386Z] Executed 'Functions.ingest' (Failed, Id=2545ed75-d31e-4714-bda6-031cdf56ff7a, Duration=1393ms)
[2021-08-24T17:28:46.386Z] System.Private.CoreLib: Exception while executing function: Functions.ingest. System.Private.CoreLib: Result: Failure
[2021-08-24T17:28:46.387Z] Exception: RuntimeError: Cannot run the event loop while another loop is running
[2021-08-24T17:28:46.387Z] Stack: File "/usr/lib/azure-functions-core-tools-3/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 394, in _handle__invocation_request
[2021-08-24T17:28:46.387Z] call_result = await self._run_async_func(
[2021-08-24T17:28:46.387Z] File "/usr/lib/azure-functions-core-tools-3/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 608, in _run_async_func
[2021-08-24T17:28:46.387Z] return await ExtensionManager.get_async_invocation_wrapper(
[2021-08-24T17:28:46.387Z] File "/usr/lib/azure-functions-core-tools-3/workers/python/3.9/LINUX/X64/azure_functions_worker/extension.py", line 147, in get_async_invocation_wrapper
[2021-08-24T17:28:46.387Z] result = await function(**args)
[2021-08-24T17:28:46.387Z] File "/home/jon/code/author-db-app/ingest/main.py", line 152, in main
[2021-08-24T17:28:46.388Z] return AsgiMiddleware(app).handle(req, context)
[2021-08-24T17:28:46.388Z] File "/home/jon/code/author-db-app/ingest/http_asgi.py", line 123, in handle
[2021-08-24T17:28:46.388Z] return self._handle(req, context)
[2021-08-24T17:28:46.388Z] File "/home/jon/code/author-db-app/ingest/http_asgi.py", line 130, in _handle
[2021-08-24T17:28:46.388Z] asgi_response = self.loop.run_until_complete(
[2021-08-24T17:28:46.388Z] File "/usr/lib/python3.9/asyncio/base_events.py", line 618, in run_until_complete
[2021-08-24T17:28:46.389Z] self._check_running()
[2021-08-24T17:28:46.389Z] File "/usr/lib/python3.9/asyncio/base_events.py", line 580, in _check_running
[2021-08-24T17:28:46.389Z] raise RuntimeError(
Normally (non-serverless), I'd do this initialisation here, but this doesn't get hit with the new ASGIHandler Entry point
@app.on_event("startup")
async def startup_db_client():
await start_mongo()
Any ideas, greatly appreciated!
Thanks
I've been using this and it works really nice.
I have a problem now that i need to capture the context from que function (to get context.function_directory so i can make it work with a file share).
Any hint on how to make it work in this?
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
return AsgiMiddleware(app).handle(req, context)
Hi, and first of all thank you for your work ! I'm currently working on a webapp hosted on Azure and wanted to go serverless; your AsgiMiddleware was a huge help.
However I'm trying to use with with a FastAPI app where I instantiate a MongoClient at the startup of the app (much like here : https://github.com/markqiu/fastapi-mongodb-realworld-example-app/tree/master/app).
When I publish my function and test it, the Mongo client doesnt seem to be set. Maybe because the startup events of the app are never triggered ? Do you have any idea on how I could make this work ? Thanks !
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.