【问题标题】:Azure use python flask framework for function appAzure 为函数应用使用 python 烧瓶框架
【发布时间】:2019-03-14 03:39:00
【问题描述】:

我看到 Azure 现在在函数应用中支持 Python(预览版)。我有一个现有的 Flask 应用程序,想知道是否可以将其部署为函数应用程序而无需进行重大更改?

我已经阅读了在函数应用程序中使用 Python (https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python) 的 Azure 教程,但没有使用 Flask 框架...

有人有这方面的经验吗?

【问题讨论】:

    标签: python azure flask azure-functions


    【解决方案1】:

    我尝试了不同的方法将 Azure Functions for Python 与 Flask 框架集成。最后,我通过app.test_client() 在名为TryFlask 的HttpTrigger 函数中成功实现了。

    这是我的示例代码,如下所示。

    import logging
    import azure.functions as func
    from flask import Flask, request
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return 'Hello World!'
    
    @app.route('/hi')
    def hi():
        return 'Hi World!'
    
    @app.route('/hello')
    @app.route('/hello/<name>', methods=['POST', 'GET'])
    def hello(name=None):
        return name != None and 'Hello, '+name or 'Hello, '+request.args.get('name')
    
    def main(req: func.HttpRequest) -> func.HttpResponse:
        logging.info('Python HTTP trigger function processed a request.')
        uri=req.params['uri']
        with app.test_client() as c:
            doAction = {
                "GET": c.get(uri).data,
                "POST": c.post(uri).data
            }
            resp = doAction.get(req.method).decode()
            return func.HttpResponse(resp, mimetype='text/html')
    

    为了在本地和 Azure 上进行测试,通过 URL http(s)://&lt;localhost:7071 or azurefunchost&gt;/api/TryFlask 访问 URL /、'/hi' 和 /hello,并在浏览器中使用查询字符串 ?uri=/?uri=/hi?uri=/hello/peter-pan,以及使用查询字符串?uri=/hello/peter-pan 对上述相同的 url 执行POST 方法,这些都有效。本地查看结果如下图,云端相同。

    注意:在我的解决方案中,url 必须是http(s)://&lt;localhost:7071 or azurefunchost&gt;/&lt;routePrefix defined in host.json, default is api&gt;/&lt;function name&gt;?uri=&lt;uri defined in app.route, like / or /hi or /hello, even /hello/peter-pan?name=peter&gt;

    【讨论】:

    • 这适用于简单的情况,但不适用于 POST 请求的 JSON 有效负载! main() 包装器不完整。
    • @Peter Pan 我有一个与这篇文章相关的问题。能打扰你几分钟吗?如果需要,我很乐意发布新问题。干杯
    • @PeterPan 你能帮我回答以下问题吗-stackoverflow.com/questions/68121920/…
    【解决方案2】:

    Flask 应用程序只是一个 WSGI 应用程序。 WSGI 是一个相当简单的接口(参见http://ivory.idyll.org/articles/wsgi-intro/what-is-wsgi.html。因此,与其使用 test_client() 作为中间件连接到 Azure 函数环境,不如使用适当的 wsgi 包装器实现,它调用 app=Flask() 对象。

    https://github.com/vtbassmatt/azf-wsgi 中有一个不错的 Azure Python wsgi 包装器实现“azf-wsgi”。

    为了将 azf-wsgi 包装器与 Flask 一起使用,我发现使用中间件将 URL:s 从 /api/app 重写为 / 非常有用,因此在开发时,我不需要知道我的 Flask 在哪里应用程序被安装。 额外的好处是我的 main.py 只是一个普通的 Flask 应用程序,我可以在不使用 Azure 函数环境的情况下在本地运行它(更快)。

    附上我的 Azure 函数的 HttpTriggerApp/__init__.py。 myFlaskApp 文件夹位于 HttpTriggerApp 下。记得在 http-trigger 和 main.py 中使用 rlative import (from . import myHelperFooBar)。

    对于 host.json 和 function.json,请按照 azf-wsgi 说明进行操作。

    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)
    

    【讨论】:

      【解决方案3】:

      Flask 现在可以开箱即用地与 Python Azure Functions 一起使用 -> 请参阅 https://github.com/Azure/azure-functions-python-library/pull/45

      【讨论】:

        猜你喜欢
        • 2018-01-22
        • 2016-07-28
        • 2018-08-17
        • 2018-02-22
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多