Created
June 4, 2023 22:37
-
-
Save timothypage/94ab5979c01c4cc78da5f12458e9fb3a to your computer and use it in GitHub Desktop.
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
# pip install fastapi "uvicorn[standard]" numpy matplotlib cairocffi | |
# run with uvicorn index:app (--reload) | |
import matplotlib | |
import matplotlib.pyplot as plt | |
import numpy as np | |
import io | |
from io import BytesIO | |
from fastapi import FastAPI | |
from fastapi.responses import StreamingResponse | |
# brew install cairo OR apt install libcairo2-dev | |
# pip install cairocffi (or pycairo, if that floats your boat) | |
matplotlib.use('Cairo') | |
app = FastAPI() | |
@app.get("/") | |
def read_root(): | |
return {"Hello": "World"} | |
@app.get("/plot.png") | |
def get_plot(): | |
image_buffer = BytesIO() | |
x = np.linspace(0, 2 * np.pi, 200) | |
y = np.sin(x) | |
fig, ax = plt.subplots() | |
ax.plot(x, y) | |
plt.savefig(image_buffer, format="png") | |
plt.close() | |
image_buffer.seek(0) | |
return StreamingResponse(image_buffer, media_type="image/png") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment