作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在学习使用 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
)
浏览器中的结果如下图。
我的static-file
的文件结构api如下。
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/
我是一名优秀的程序员,十分优秀!