Created
October 14, 2022 14:30
-
-
Save deeplook/f8208fbfbba94bf460a8903e978701f7 to your computer and use it in GitHub Desktop.
Try serving geopandas/matplotlib content with Flask.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Try serving geopandas/matplotlib content with Flask. | |
Run with: | |
flask --app app run | |
""" | |
from flask import Flask, Response | |
app = Flask(__name__) | |
import io | |
import base64 | |
import random | |
from matplotlib.figure import Figure | |
# https://github.com/matplotlib/matplotlib/blob/944b99a826a1b3509cbf7add49dccb14db9240fb/examples/user_interfaces/web_application_server_sgskip.py | |
@app.route("/nopyplot") | |
def nopyplot(): | |
# works | |
# Generate the figure **without using pyplot**. | |
fig = Figure() | |
ax = fig.subplots() | |
ax.plot([1, 2]) | |
# Save it to a temporary buffer. | |
buf = io.BytesIO() | |
fig.savefig(buf, format="png") | |
# Embed the result in the html output. | |
data = base64.b64encode(buf.getbuffer()).decode("ascii") | |
return f"<img src='data:image/png;base64,{data}'/>" | |
import io | |
import random | |
from matplotlib.backends.backend_agg import FigureCanvasAgg | |
from matplotlib.figure import Figure | |
@app.route('/lineplot') | |
def mpl_plot_png(): | |
# works, too | |
fig = Figure() | |
axis = fig.add_subplot(1, 1, 1) | |
xs = range(100) | |
ys = [random.randint(1, 50) for x in xs] | |
axis.plot(xs, ys) | |
output = io.BytesIO() | |
FigureCanvasAgg(fig).print_png(output) | |
return Response(output.getvalue(), mimetype='image/png') | |
import geopandas | |
@app.route('/geoplot') | |
def gdf_plot_png(): | |
# crashes the process | |
path = geopandas.datasets.get_path("nybb") | |
df = geopandas.read_file(path) | |
df_wm = df.to_crs(epsg=3857) # Web Mercator | |
# The following line crashes with: | |
# ... python3.10/site-packages/geopandas/plotting.py:673: UserWarning: | |
# Starting a Matplotlib GUI outside of the main thread will likely fail. | |
ax = df_wm.plot(figsize=(4, 4), alpha=0.5, edgecolor="k") | |
fig = ax.figure | |
output = io.BytesIO() | |
FigureCanvasAgg(fig).print_png(output) | |
return Response(output.getvalue(), mimetype="image/png") | |
if __name__ == "__main__": | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment