question

ArezooAbdollahi-3686 avatar image
0 Votes"
ArezooAbdollahi-3686 asked MayankBargali-MSFT commented

Azure 500 internall server error when using plotly for data visualization

Hello everyone,

I have a question regarding deploying a function in the Azure portal.

I had a project for data visualizations that I wrote that code with Matplotlib and I deployed it on Azure, and right now is on production.

Then, I added some other graphs but this time I used Plotly. I am able to run the Azure function locally and I don’t have any problems with it. It will return the value correctly with status 200ok on Postman. However, when I deploy it on the Azure portal, I got status 500 internal servers!

Can anyone help me with this?

Note that I have a requirements file that has Plotly and everything I need on it in the same folder that I am deploying. Should I install plotly on Microsoft Azure myself?!? I assume that it can read from the requirements file

Note that I don’t have this problem with the graphs that I used Matplotlib for them. I just have this problem with the graphs I used Plotly for them.

Below, I put the small sample of my code that I can run it locally on postman, and it will return status 200Ok with string but when I deploy it on Azure, I receive 500 internal server problem


import logging
import azure.functions as func
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
#import cv2
import base64
import os
import tempfile
from cv2 import cv2
import plotly.graph_objs as go


def graphing(shortID, data, labels, dims = (600, 300), format = 'png', **render_details):
    if shortID == 'M':
        print("shortID", shortID)
        myfig = go.Figure(go.Bar(
            x=data[0],
            y=data[1],
            orientation='h'))
        
        tempFilePath = tempfile.gettempdir()

        try:
            file_path = os.path.join(tempFilePath, 'plot.'+ format)
            myfig.write_image(file_path)
            img = cv2.imread(file_path)
            _, im_arr = cv2.imencode('.'+format, img)
            im_bytes = im_arr.tobytes()
            response = base64.b64encode(im_bytes)
            os.remove(file_path)
        except:
            file_path = os.path.join(tempFilePath, 'plot.png')
            myfig.write_image(file_path)
            img = cv2.imread(file_path)
            _, im_arr = cv2.imencode('.png', img)
            im_bytes = im_arr.tobytes()
            response = base64.b64encode(im_bytes)
            #response = im_b64.decode("utf-8")
            os.remove(file_path)

    return response

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    shortID = req.params.get('shortID')
    data = req.params.get('data')
    labels = req.params.get('labels')
    image_format =req.params.get('format')
    if not shortID or not data or not labels:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            shortID = req_body.get('shortID')   
            data = req_body.get('data')
            labels = req_body.get('labels')
            image_format = req_body.get('format')
    #print("image_format", image_format)
    if shortID and data and labels:
        im_str = graphing(shortID, data, labels, format = image_format)
    
    

    if shortID:
        if image_format:
            try:
                print("try image")
                return func.HttpResponse(body=im_str, mimetype='image/'+image_format)
            except:
                print("except image")
                return func.HttpResponse(body=im_str, mimetype='image/png')
        else:
            print("else image")
            return func.HttpResponse(body=im_str, mimetype='image/png')
    else:
        return func.HttpResponse(
             "Please pass required parameters on the query string or in the request body",
             status_code=400
        )
azure-functions
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The above code is just the portion of my code which again I can run it locally and I receive 200ok status, with the string that it returns but I have a problem deploying it on Azure.

The json file I use to test my code is as follows:


{
"shortID": "M",
"data": [[20, 14, 23],["Dispositions","Parenting","Education"], []],
"labels": ["None", "None"],
"format": "jpg"
}

0 Votes 0 ·

1 Answer

MayankBargali-MSFT avatar image
0 Votes"
MayankBargali-MSFT answered MayankBargali-MSFT commented

Hi @ArezooAbdollahi-3686

I will suggest you to look into application insights logs to get more information/detailed exceptions causing the 500 error.
If you have not enabled the application insights for your function app then I will suggest you to enable it, repro the issue and analyze/look into application insights logs to know the cause of 500 error. You can refer to here to analyze telemetry data.

As per the code, I can see you are using multiple libraries and I will suggest you to verify whether you are adding all the required libraries in your requirement.txt file as this couldn't be one of the reasons for the 500 error where the function couldn't find the library.

import logging
import azure.functions as func
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import cv2
import base64
import os
import tempfile
from cv2 import cv2
import plotly.graph_objs as go

Hope the above helps you to resolve the issue. Feel free to reach out to me if you need any assistance.

· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for your comment. I am new to Azure, but I took a look at my application insight and I didn't find anything useful. I just saw some charts that are showing the failure cases.

I believe I added everything that I installed in my requirement files. Also, once I used pip freeze, and I added all the libraries that it gave me and I added them to the requirements file.


I deployed it with both versions but I didn't see any difference.

0 Votes 0 ·

**I find what is the problem! The problem is that when I have this line on my code:

offline.plot(fig2, auto_open=False, output_type='file', filename='abc.html')

`
I don't have this line here, but this was the main thing that cause problem for me.
It tries to modify files in a read-only file system. This doesn't make any problem in the local deployment but it will create a problem in Azure deployment.

1 Vote 1 ·

@ArezooAbdollahi-3686 Glad to know that you were able to find the root cause of the issue.

0 Votes 0 ·