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

问题描述 投票:0回答:3

我正在尝试使用 FastAPI / Uvicorn 在 Google Colab 上运行一个“本地”网络应用程序,就像我见过的一些 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
python google-colaboratory fastapi uvicorn
3个回答
32
投票

您可以使用 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)

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

这不会进行任何多重处理或热重载,但如果您只想从 Jupyter 快速运行简单的 ASGI 应用程序,则可以完成工作。

这也可以使用 Hypercorn 来实现。


编辑:上面的代码在本地 Jupyter 中运行良好,但由于 Colab 仍然不支持顶级

await
语句(截至 2022 年 7 月),您需要将上面代码片段的最后一行替换为像这样的东西:

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

0
投票

有时我们会收到如下错误:

PyngrokNgrokError:ngrok 进程启动时出错:身份验证失败:使用 ngrok 需要经过验证的帐户和 authtoken。

  • 首先我们必须创建一个身份验证令牌并将其设置为我们正在运行的 ngrok

  • 前往ngrok隧道

  • 创建身份验证隧道并复制身份验证令牌

您还可以简单地从 https://dashboard.ngrok.com/get-started/your-authtoken

获取身份验证令牌
  • 现在在您的代码中添加令牌

!pip 安装 pyngrok
导入nest_asyncio
从 pyngrok 导入 ngrok
进口uvicorn

# 从 https://dashboard.ngrok.com/get-started/your-authtoken 获取您的 authtoken
auth_token =“您的AUTH_TOKEN”

# 设置授权令牌
ngrok.set_auth_token(auth_token)

# 连接到 ngrok
ngrok_tunnel = ngrok.connect(8000)

# 打印公共 URL
print('公共网址:', ngrok_tunnel.public_url)

# 应用nest_asyncio
Nest_asyncio.apply()

# 运行 uvicorn 服务器
uvicorn.run(应用程序,端口=8000)

© www.soinside.com 2019 - 2024. All rights reserved.