Azure use python flask framework for function app

前端 未结 3 1268
后悔当初
后悔当初 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条回答
  •  -上瘾入骨i
    2021-01-21 03:42

    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/', 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):///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):////?uri=.

提交回复
热议问题