我尝试了不同的方法将azure的python函数与flask框架集成。最后,我在名为
TryFlask
通过
app.test_client()
.
这是我的示例代码,如下所示。
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
/
,‘嗨’
/hello
通过URL
http(s)://<localhost:7071 or azurefunchost>/api/TryFlask
带查询字符串
?uri=/
,
?uri=/hi
和
?uri=/hello/peter-pan
在浏览器中,并执行
POST
方法使用查询字符串访问上面的同一URL。
?uri=/hello/彼得潘
,这些都是工作。请将结果作为下面的本地数字查看,与云上的结果相同。
注意:在我的解决方案中,url必须是
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>
.