FileResource Object

I keep getting the error: AttributeError: ‘FileResource’ object has no attribute ‘get_content’

How do I resolve it?

from viktor import ViktorController
from viktor.parametrization import ViktorParametrization, FileField
from viktor.views import PlotlyView
import plotly.graph_objs as go
import numpy as np

class Parametrization(ViktorParametrization):
    file = FileField('Upload Numbers', file_types=['.txt'])

class Controller(ViktorController):
    label = 'Rainbow Plot'
    parametrization = Parametrization

    @PlotlyView('Plot', duration_guess=1)
    def get_plot(self, params, **kwargs):
        file_content = params.file.get_content().decode('utf-8')
        numbers = np.array([float(line.strip()) for line in file_content.splitlines() if line.strip().isdigit()])

        # Generate a rainbow plot using Plotly
        colors = ['hsl(' + str(hue) + ', 100%, 50%)' for hue in np.linspace(0, 360, len(numbers))]
        data = [go.Bar(x=list(range(len(numbers))), y=numbers, marker=dict(color=colors))]
        layout = go.Layout(title='Rainbow Plot of Numbers', xaxis=dict(title='Index'), yaxis=dict(title='Value'))
        fig = go.Figure(data=data, layout=layout)

        return fig

Hi Toufique,

The FileResource class doesn’t have a get_content() method, see the documentation for more information.

To access the VIKTOR File object from the FileResource call file property. To access the contents of the VIKTOR File object you can use getvalue() or getvalue_binary()

In your code this would look like the following:

from viktor import ViktorController
from viktor.parametrization import ViktorParametrization, FileField
from viktor.views import PlotlyView
import plotly.graph_objs as go
import numpy as np

class Parametrization(ViktorParametrization):
    file = FileField('Upload Numbers', file_types=['.txt'])

class Controller(ViktorController):
    label = 'Rainbow Plot'
    parametrization = Parametrization

    @PlotlyView('Plot', duration_guess=1)
    def get_plot(self, params, **kwargs):
        file_content = params.file.file.getvalue('utf-8')
        numbers = np.array([float(line.strip()) for line in file_content.splitlines() if line.strip().isdigit()])

        # Generate a rainbow plot using Plotly
        colors = ['hsl(' + str(hue) + ', 100%, 50%)' for hue in np.linspace(0, 360, len(numbers))]
        data = [go.Bar(x=list(range(len(numbers))), y=numbers, marker=dict(color=colors))]
        layout = go.Layout(title='Rainbow Plot of Numbers', xaxis=dict(title='Index'), yaxis=dict(title='Value'))
        fig = go.Figure(data=data, layout=layout)

        return fig
1 Like

Thanks, this helps! I made further modifications to the code as well and now it is running alright!