Azure 为函数应用使用 python 烧瓶框架

2022-01-17 00:00:00 python flask azure azure-functions

问题描述

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

我已阅读在函数应用程序中使用 Python 的 Azure 教程 (

注意:在我的解决方案中,url 必须是 http(s):////<函数名>?uri=<uri定义在app.route中,如/或/hi或/hello,甚至/hello/peter-pan?name=peter>.

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 major changes?

I have read through the Azure tutorials that uses Python in function apps (https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python), however not with the flask framework...

Has anyone any experience with it?

解决方案

I tried different ways to integrate Azure Functions for Python with Flask framework. Finally, I did it success in my HttpTrigger function named TryFlask via app.test_client().

Here is my sample code, as below.

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')

For testing on local and Azure, to access the urls /, '/hi' and /hello via the url http(s)://<localhost:7071 or azurefunchost>/api/TryFlask with query string ?uri=/, ?uri=/hi and ?uri=/hello/peter-pan in browser, and to do the POST method for the same url above with query string ?uri=/hello/peter-pan, these are all work. Please see the results as the figures locally below, the same on cloud.

Note: In my solution, the url must have to be http(s)://<localhost:7071 or azurefunchost>/<routePrefix defined in host.json, default is api>/<function name>?uri=<uri defined in app.route, like / or /hi or /hello, even /hello/peter-pan?name=peter>.

相关文章