2

I'm playing with Flask and Python 3.5. I want to show a matplotplib chart on a website. I found this example https://gist.github.com/wilsaj/862153

I made minor modifications to the StringIO part since I'm using 3.5 version of Python.

@bp.route("/simple.png")
def simple():
    import datetime
    import io
    import numpy as np
    import random

    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    fig=Figure()
    ax=fig.add_subplot(111)
    x=[]
    y=[]
    now=datetime.datetime.now()
    delta=datetime.timedelta(days=1)
    for i in range(10):
        x.append(now)
        now+=delta
        y.append(random.randint(0, 1000))
    ax.plot_date(x, y, '-')
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    png_output = io.BytesIO()
    png_output_text = np.genfromtxt(png_output, delimiter=",")
    canvas.print_png(png_output_text)
    response=make_response(png_output_text.getvalue())
    response.headers['Content-Type'] = 'image/png'
    return response

Error I'm receiving:

Traceback (most recent call last):
  File "c:\proofdevelopment\flask\flask\app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "c:\proofdevelopment\flask\flask\app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "c:\proofdevelopment\flask\flask\app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "c:\proofdevelopment\flask\flask\_compat.py", line 33, in reraise
    raise value
  File "c:\proofdevelopment\flask\flask\app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "c:\proofdevelopment\flask\flask\app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\ProofDevelopment\flask\examples\flaskr\flaskr\blueprints\flaskr.py", line 107, in simple
    canvas.print_png(png_output_text)
  File "C:\Users\nmartinez\AppData\Local\Continuum\miniconda3\envs\py35\lib\site-packages\matplotlib\backends\backend_agg.py", line 526, in print_png
    self.figure.dpi, metadata=metadata)
TypeError: Object does not appear to be a 8-bit string path or a Python file-like object

I just want to run that 'simple' example and I haven't been able to :(

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Fran Martinez
  • 677
  • 4
  • 15
  • 36
  • Please post the *entire* error message including the traceback. This is essential because it will tell us which line caused the error message. Otherwise, we have to guess, and we may or may not guess correctly. Or we may just skip your question and move on to one that gives us more information about the problem. – kindall Jan 26 '18 at 20:18
  • Traceback has lots of useful context – JacobIRR Jan 26 '18 at 20:18
  • that doesnt seem to be the entire traceback – Michael Ilie Jan 26 '18 at 20:22
  • Where did `png_output_text = np.genfromtxt(png_output, delimiter=",")` come from? – Martijn Pieters Jan 26 '18 at 20:23
  • From Pierre's answer here: https://stackoverflow.com/questions/11914472/stringio-in-python3 – Fran Martinez Jan 26 '18 at 20:24
  • @Codinghierarchy: you misunderstood the answer then. The code in the *question* uses `np.genfromtxt()` and the answer corrected what object is being passed in. – Martijn Pieters Jan 26 '18 at 20:38

3 Answers3

2

I'm not sure why you added the np.genfromtxt() call. The following lines to create the in-memory file object are enough; these are the last lines in the view function, starting at your png_output line:

png_output = io.BytesIO()
canvas.print_png(png_output)
response = make_response(png_output.getvalue())
response.headers['Content-Type'] = 'image/png'
return response

With those changes, the code produces a plot:

enter image description here

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1
x_train=np.array(list(map(img_preprocess,x_train)))
x_valid=np.array(list(map(img_preprocess,x_valid)))

bit shows object-does-not-appear-to-be-a-8-bit-string-path-or-a-python-file-like-object

This Error is because Here you already changed shape of x_train by executing x_train=np.array(list(map(img_preprocess,x_train))) this line, so x_train is updated now and again if you will give x_train as input to the x_train=np.array(list(map(img_preprocess,x_train))) function then it will give this error

solution: reset your python kernel and run all code in sequence again.

RamPrakash
  • 1,687
  • 3
  • 20
  • 25
-1
x_train=np.array(list(map(img_preprocess,x_train)))
x_valid=np.array(list(map(img_preprocess,x_valid)))
bit shows object-does-not-appear-to-be-a-8-bit-string-path-or-a-python-file-like-object

Whats's the problem behind it?

roschach
  • 8,390
  • 14
  • 74
  • 124