A
A
Alexey Samoilov2015-04-02 11:01:50
Flask
Alexey Samoilov, 2015-04-02 11:01:50

How to plot in Flask on Google App Engine?

Hello.

To build a graph, I use this recipe (first building and saving in .png, then .png in the HTML body is taken from the folder).

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.plot(x_1, y_1, 'r-',
             x_2, y_2, 'b-')

plt.savefig('static/img/plot.png')


<img src="static/img/plot.png" alt="Image Placeholder" height="400">


But in the case of GAE, matplotlib does not work quite correctly.
Yes, I created a separate lib folder and put matplotlib with all the dependencies there, but even in this case, I get all sorts of errors:
ImportError: dynamic module does not define init function (init_path)

lib/numpy/core/__init__.py", line 6 , in
from .import multiarray
ImportError: cannot import name multiarray


Maybe someone has already encountered such a bunch and knows the recipe for plotting?Perhaps using other libraries.Thanks

.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Samoilov, 2015-04-02
@tibhar940

I'll answer my own question.
Perhaps for the same lamers like me, it will be useful.
1. Before using any library in GAE, you need to make sure if it is supported or not. Follow this link: https://cloud.google.com/appengine/docs/python/too...
2. If it is supported (as in the case of matplotlib), look to what extent: look Supported version. We have this "1.2.0" "latest"
3. Based on this, we adjust our app.yaml libraries file :
-
name: jinja2
version: "2.6"
- name: markupsafe
version: "0.15"
- name: matplotlib
version: "latest "

4. Then already in our main.py (well, or views.py - depending on how you called the file that processes the views and depending on the project structure) we do the import as usual

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

The final recipe for plotting in Flask using matplotlib in GAE looks like this:
import StringIO
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

def func():
    plt.plot(x1, y1, 'r-',
                 x2, y2 'b-')

    output = StringIO.StringIO()
    plt.savefig(output, format="png")
    img = 'data:image/png;base64,%s' % output.getvalue().encode("base64").strip()
    return img

## Само представление

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
@app.route('/index')
def index():
    img = func() ## Я создал отдельную функцию (см. выше) для формирования и вызываю её при заходе на страницу
    return render_template(
        'index.html',
        img = img)

<img src="{{ img }}" alt="Image Placeholder" height="400">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question