Azure为功能应用程序使用python flask框架 [英] Azure use python flask framework for function app
问题描述
我看到Azure现在在功能应用程序中支持Python(预览版).我有一个现有的Flask应用程序,想知道是否可以在不进行重大更改的情况下将该功能部署为功能应用程序?
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?
我已阅读了在功能应用程序中使用Python的Azure教程( https://docs.microsoft.com/zh-cn/azure/azure-functions/functions-reference-python ),但不包括flask框架...
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...
有人有经验吗?
推荐答案
我尝试了多种方法来将Azure Python函数与Flask框架集成在一起.最终,我通过app.test_client()
在名为TryFlask
的HttpTrigger函数中成功完成了该任务.
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')
要在本地和Azure上进行测试,请在浏览器中通过查询字符串?uri=/
,?uri=/hi
和?uri=/hello/peter-pan
通过URL http(s)://<localhost:7071 or azurefunchost>/api/TryFlask
访问URL /
,'/hi'和/hello
,以及使用查询字符串?uri=/hello/peter-pan
对上述相同的url执行POST
方法,所有这些工作.请在下面的本地图中查看结果,在云上也是如此.
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.
注意:在我的解决方案中,网址必须为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>
.
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>
.
这篇关于Azure为功能应用程序使用python flask框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!