gpt4 book ai didi

python - 如何在 HTTP 响应中返回 HTML 文件(Azure-Functions)

转载 作者:行者123 更新时间:2023-12-02 22:56:46 25 4
gpt4 key购买 nike

我正在学习使用 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
)

我想要的是这样的:

return func.HttpResponse("\index.html")

我该怎么做?

最佳答案

假设您正在遵循官方快速入门教程 Create an HTTP triggered function in Azure 要学习适用于 Python 的 Azure Function,您创建了一个名为 static-file 的函数处理路径 static-file 中的这些静态文件或您想要的其他路径 MyFunctionProj喜欢 index.html , logo.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
)

浏览器中的结果如下图。

enter image description here

我的static-file的文件结构api如下。

enter image description here

index.html的内容文件如下。

<html>
<head></head>
<body>
<h3>Hello, world!</h3>
<img src="http://localhost:7071/api/static-file?name=logo.jpg"></img>
</body>
</html>

注意:对于在本地运行,index.html文件将可以正常显示 logo.jpg 。如果部署到Azure,需要添加查询参数code到属性末尾src标签 img ,如<img src="http://<your function name>.azurewebsites.net/api/static-file?name=logo.jpg&code=<your code for /api/static-file>"></img> .

希望有帮助。

关于python - 如何在 HTTP 响应中返回 HTML 文件(Azure-Functions),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57355106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com