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

标签 python google-colaboratory fastapi uvicorn

我正在尝试使用 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

最佳答案

您可以使用 ngrok 将端口导出为外部 url。基本上,ngrok 获取本地主机上可用/托管的内容,并使用临时公共(public) URL 将其公开到 Internet。
首先安装依赖

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

关于python - 如何在 Google Colab 中运行 FastAPI/Uvicorn?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63833593/

相关文章:

python - 如何将 m4a 文件从 FastAPI 发送到 OpenAI 转录

python - 无法从 FastAPI 中正在运行的事件循环调用 asyncio.run()

python - `with return .. return` 是无法访问的代码吗?

jupyter-notebook - Google Colab 中 Jupyter Notebook 的所有单元输出消失

python - Pandas 数据框到嵌套计数器字典

python-3.x - 如何为模型准备测试集形状。使用 keras 和 tensorflow 进行评估?

tensorflow - TF2 : Compute gradients in keras callback in non-eager mode

python - FastAPI:如何访问依赖项内的 APIRoute 对象

python - 如何在 flask 后端运行 python 脚本?

python - 如何以推荐的 Pythonic 方式在 Python for 循环中使用 2 个变量?