Am4*_*eur 4 html python http azure azure-functions
我正在学习使用 azure-functions,我想知道如何在这段代码上返回 HTML 文件。(azure-functions 的初始 python 代码)
import logging
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = req.params.get('name')
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get('name')
if name:
return func.HttpResponse(f"Hello {name}!")
else:
return func.HttpResponse(
"Please pass a name on the query string or in the request body",
status_code=400
)
Run Code Online (Sandbox Code Playgroud)
我想要的是这样的:
return func.HttpResponse("\index.html")
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
假设您按照官方快速入门教程Create an HTTP triggered function in Azure学习 Azure Function for Python,然后您创建了一个名为 的函数static-file来处理路径static-file或您想要的其他路径中的这些静态文件,MyFunctionProj等等。index.htmllogo.jpg
这是我的示例代码,如下所示。
import logging
import azure.functions as func
import mimetypes
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = req.params.get('name')
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get('name')
if name:
#return func.HttpResponse(f"Hello {name}!")
path = 'static-file' # or other paths under `MyFunctionProj`
filename = f"{path}/{name}"
with open(filename, 'rb') as f:
mimetype = mimetypes.guess_type(filename)
return func.HttpResponse(f.read(), mimetype=mimetype[0])
else:
return func.HttpResponse(
"Please pass a name on the query string or in the request body",
status_code=400
)
Run Code Online (Sandbox Code Playgroud)
浏览器中的结果如下图。
我的 api 的文件结构static-file如下。
文件内容index.html如下。
<html>
<head></head>
<body>
<h3>Hello, world!</h3>
<img src="http://localhost:7071/api/static-file?name=logo.jpg"></img>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
注意:对于在本地运行,该index.html文件可以正常显示logo.jpg. 如果部署到Azure,需要在tag 的code属性末尾添加查询参数,例如。srcimg<img src="http://<your function name>.azurewebsites.net/api/static-file?name=logo.jpg&code=<your code for /api/static-file>"></img>
希望能帮助到你。