I'm learning to use azure-functions and I want to know how can I return an HTML file on this piece of code. (the initial python code for azure-functions)
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
)
What I want is something like:
return func.HttpResponse("\index.html")
How can I do this?
Assumed that you are following the offical Quickstart tutorial Create an HTTP triggered function in Azure to learn Azure Function for Python, then you created a function named static-file to handle these static files in the path static-file or other path you want of MyFunctionProj like index.html, logo.jpg and so on.
Here is my sample code to do that as below.
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
)
The result in browser as the figure below.

The file structure of my static-file api as below.

The content of the index.html file is as below.
<html>
<head></head>
<body>
<h3>Hello, world!</h3>
<img src="http://localhost:7071/api/static-file?name=logo.jpg"></img>
</body>
</html>
Note: for running on local, the index.html file will works fine to display logo.jpg. If deploy to Azure, you need to add the query parameter code to the end of property src of tag img, such as <img src="http://<your function name>.azurewebsites.net/api/static-file?name=logo.jpg&code=<your code for /api/static-file>"></img>.
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With