如何在 Google Colab 中 运行 FastAPI / Uvicorn?

How to run FastAPI / Uvicorn in Google Colab?

我正在尝试 运行 Colab 上 Google 使用 FastAPI / Uvicorn 的“本地”网络应用程序,就像我见过的一些 Flask 应用程序示例代码一样,但无法使其正常工作。有没有人能够做到这一点?欣赏一下。

已成功安装 FastAPI 和 Uvicorn

!pip install FastAPI -q
!pip install uvicorn -q

示例应用程序

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

运行 次尝试

#attempt 1
if __name__ == "__main__":
    uvicorn.run("/content/fastapi_002:app", host="127.0.0.1", port=5000, log_level="info")

#attempt 2
#uvicorn main:app --reload
!uvicorn "/content/fastapi_001.ipynb:app" --reload

您可以使用 ngrok 将端口导出为外部 url。基本上,ngrok 在您的本地主机上获取一些东西 available/hosted 并通过临时 public URL.

将其公开到互联网

首先安装依赖[=​​13=]

!pip install fastapi nest-asyncio pyngrok uvicorn

创建您的应用程序

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)

@app.get('/')
async def root():
    return {'hello': 'world'}

然后运行下来。

import nest_asyncio
from pyngrok import ngrok
import uvicorn

ngrok_tunnel = ngrok.connect(8000)
print('Public URL:', ngrok_tunnel.public_url)
nest_asyncio.apply()
uvicorn.run(app, port=8000)