如何在Google Colab中运行FastAPI / Uvicorn? 已成功安装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会将一些可用的东西/托管在您的本地主机上,并使用一个临时的公共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)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...