29 fastapi
29.1 api文件
from fastapi import FastAPI
= FastAPI()
app
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
@app.get("/echo")
def echo(msg: str = ""):
return {"msg": f"The message is: '{msg}'"}
@app.get("/plot")
def plot():
import numpy as np
import matplotlib.pyplot as plt
= np.random.randn(100)
rand
plt.hist(rand)"hist.png")
plt.savefig(
@app.post("/sum")
def sum_numbers(a: float, b: float):
return {"result": a + b}
29.2 在虚拟环境中打开
cd myapp
source myapp/bin/acitvate
cd api uvicorn api:app --host 0.0.0.0 --port 8052
29.3 使用
在浏览器中输入网址和参数
<www.mmphcrc.com:8052>
<www.mmphcrc.com:8052/sum/?a=2&b=3>