Azure use python flask framework for function app

前端 未结 3 1265
后悔当初
后悔当初 2021-01-21 03:11

I saw that Azure now supports Python (preview) in the function apps. I have a existing Flask app and was wondering if it\'s possible to deploy that one as a function app without

3条回答
  •  北海茫月
    2021-01-21 04:09

    Flask app is just an WSGI application. WSGI is a rather simple interface (see http://ivory.idyll.org/articles/wsgi-intro/what-is-wsgi.html. So instead of using test_client() as middleware to connect to the Azure function environment, a proper wsgi wrapper implementation should be used, which calls the app=Flask() object.

    There is a nice Azure Python wsgi wrapper implementation "azf-wsgi" available in https://github.com/vtbassmatt/azf-wsgi.

    In order to use the azf-wsgi wrapper with Flask, I found it useful to use a middleware to rewrite the URL:s from /api/app to / so when developing, I don't need to know where my Flask app gets mounted. Additional benefit is that my main.py is just a normal Flask application, which I can run locally without using Azure functions environment (way faster).

    My HttpTriggerApp/__init__.py of Azure function is attached. The myFlaskApp-folder is located under the HttpTriggerApp. Remember to use rlative import in the http-trigger as well as main.py (from . import myHelperFooBar).

    For host.json and function.json, follow the azf-wsgi instructions.

    import logging
    import azure.functions as func
    
    # note that the package is "azf-wsgi" but the import is "azf_wsgi"
    from azf_wsgi import AzureFunctionsWsgi
    
    # Import the Flask wsgi app (note relative import from the folder under the httpTrigger-folder.
    from .myFlaskAppFolder.main import app
    
    # rewrite URL:s to Azure function mount point (you can configure this in host.json and function.json)
    from werkzeug.middleware.dispatcher import DispatcherMiddleware
    app.config["APPLICATION_ROOT"] = "/api/app"     # Flask app configuration so it knows correct endpoint urls
    application = DispatcherMiddleware(None, {
        '/api/app': app,
    })
    
    # Wrap the Flask app as WSGI application
    def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
        return AzureFunctionsWsgi(application).main(req, context)
    

提交回复
热议问题