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

13

我正在尝试在Google Colab上运行一个“本地”Web应用程序,使用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

这回答解决了你的问题吗?如何在Jupyter中运行FastAPI应用程序? - Chris
2个回答

29

你可以使用ngrok将一个端口导出为外部URL。基本上,ngrok会使用一个临时公共URL将您在本地主机上可用/托管的内容暴露到互联网上。

首先安装依赖项。

!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)

2
哇,非常令人印象深刻。在这种情况下运行它时需要注意哪些限制吗?也许我应该从一个笔记本电脑上运行服务器,并指向我正在更新的gdrive中的.py文件作为服务器主文件?我的用例是在我的笔记本电脑上本地工作的ML推理/预测API。任何见解都将不胜感激!再次感谢。 - md598

3
一种更简单的方法,无需使用ngrok或nest-asyncio:
from fastapi import FastAPI
from uvicorn import Config, Server

app = FastAPI()

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

config = Config(app)
server = Server(config=config)
await server.serve()

如果您只想快速运行一个简单的ASGI应用程序,而不进行多进程或热重载,则可以使用以下方法完成任务。

也可以使用Hypercorn实现此目的。


编辑:上述方法在本地Jupyter中可以正常工作,但由于Colab (截至2022年7月)仍不支持顶层await语句,因此您需要将上面代码片段的最后一行替换为类似以下内容的语句:

import asyncio
loop = asyncio.get_event_loop()
loop.create_task(server.serve())

谢谢您提供这个,但是当您运行它时,URL是什么?被接受的答案有一个打印语句 - 您能否分享一个适用于此方法的打印语句? - nickc
Uvicorn默认在127.0.0.1:8000上提供服务。请参见https://github.com/encode/uvicorn/blob/master/uvicorn/config.py#L212。 - Gustavo Bezerra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接