我正在学习使用azure函数,我想知道如何在这段代码中返回HTML文件。(azure函数的初始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")我该怎么做呢?
发布于 2019-08-06 10:57:07
假设你正在按照官方的快速入门教程Create an HTTP triggered function in Azure学习Python的Azure函数,然后你创建了一个名为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接口的文件结构如下。

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添加到标签img的属性src的末尾,例如<img src="http://<your function name>.azurewebsites.net/api/static-file?name=logo.jpg&code=<your code for /api/static-file>"></img>。
希望能有所帮助。
发布于 2020-03-27 23:18:46
我做的很简单,不介意内容(上传文件),它不是这样工作的:)
if command:
return func.HttpResponse(status_code=200,headers={'content-type':'text/html'},
body=
"""<!DOCTYPE html>
<html>
<body>
<form enctype = "multipart/form-data" action = "returnNameTrigger?save_file.py" method = "post">
<p>File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
""")发布于 2020-03-16 13:25:57
公认的答案不再有效。现在您需要使用上下文来查找正确的文件夹。像下面这样的代码应该可以工作。
import logging
import azure.functions as func import mimetypes
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
logging.info('processed request for home funciton')
filename = f"{context.function_directory}/static/index.html"
with open(filename, 'rb') as f:
mimetype = mimetypes.guess_type(filename)
return func.HttpResponse(f.read(), mimetype=mimetype[0])https://stackoverflow.com/questions/57355106
复制相似问题