我正在使用Python使用FastAPI构建RESTAPI服务,在我启动API服务并稍后返回后,API端点停止响应
我使用内置的:http://127.0.0.1:5000/docs打开API文档,Chrome浏览器花了很多时间等待,但没有响应。API服务器似乎已关闭或未连接
最后,我回到正在运行的API命令行窗口,按Ctrl+C停止API服务器。就在那时,API继续响应并完成工作,表明它通过URLhttp://127.0.0.1:5000/docs接收到GET请求,我在上一步中已经完成了这项工作
我不明白为什么FastAPI在闲置一段时间后会卡住,为什么按Ctrl+C会使它继续运行
这是我的密码:
from fastapi import FastAPI, BackgroundTasks
from sklearn.linear_model import LinearRegression
import uvicorn
app = FastAPI()
def train_model(tasks):
x = tasks.train_data
y = tasks.train_label
model = LinearRegression()
model.fit(x, y)
score = model.score(x, y)
print("Score:", score)
return None
@app.post("/create")
async def train(tasks, background_tasks: BackgroundTasks):
background_tasks.add_task(train_model, tasks)
return {"Received training request":True}
if __name__ = "__main__":
uvicorn.run(host = "0.0.0.0", port = 5000)
今天我使用了一个工具PM2来启动我的API,这是一个用于监控应用程序服务并在应用程序失败时自动重启程序的工具
在我使用pm2启动API之后:
pm2 start main.py
API被卡住的问题不再发生了。我想这可能是因为pm2在它失败时重新启动了我的API,但在仪表板中没有显示任何重新启动操作
现在我可以使用我的API了,但我仍然没有找出前面问题的原因。如果没有pm2,它应该可以正常工作
相关问题 更多 >
编程相关推荐