4

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?

2
  • You need a file from the response ? Like downloading something ? Commented Aug 5, 2019 at 11:41
  • No, what i need is instead of printing an f"Hello {name}", I need it to "print" an html file. With an image or something. Commented Aug 5, 2019 at 14:09

3 Answers 3

7

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.

enter image description here

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

enter image description here

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! It was exactly what I wanted and more!
what if here instead of content i want to get a file .. It means when i hit the URL .kml file (in my case) should download ... With above code i am getting the content of the file but i want file to downloaded
2

I did simple, do not mind the content (uploading a file), it is not working that way :)

  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>
""")

Comments

1

The accepted answer no longer works. Now you need to use the context to find the correct folder. Something like the code below should work.

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')
    # Returns /projectRoot/functionName/static/index.html
    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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.