Python 如何在googlecolab中运行FastAPI/Uvicorn?

Python 如何在googlecolab中运行FastAPI/Uvicorn?,python,google-colaboratory,fastapi,uvicorn,Python,Google Colaboratory,Fastapi,Uvicorn,我正试图使用FastAPI/Uvicorn在Google Colab上运行一个“本地”web应用程序,就像我见过的一些Flask应用程序示例代码一样,但无法让它运行。有人能做到这一点吗?谢谢 已成功安装FastAPI和Uvicorn 示例应用程序 运行尝试 您可以使用ngrok将端口导出为外部url。基本上,ngrok在本地主机上获取可用/托管的内容,并使用临时公共URL将其公开到internet 首先安装依赖项 !pip install fastapi nest-asyncio pyngrok

我正试图使用FastAPI/Uvicorn在Google Colab上运行一个“本地”web应用程序,就像我见过的一些Flask应用程序示例代码一样,但无法让它运行。有人能做到这一点吗?谢谢

已成功安装FastAPI和Uvicorn 示例应用程序 运行尝试
您可以使用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)

哇,非常令人印象深刻。像这样运行它时有什么限制需要注意吗?也许我应该从一个笔记本上运行服务器,并指向我的gdrive中的一个.py文件,我正在更新为主服务器?我的用例是在笔记本电脑上本地工作的ML推断/预测API。如有任何见解,将不胜感激!再次感谢。
#attempt 2
#uvicorn main:app --reload
!uvicorn "/content/fastapi_001.ipynb:app" --reload
!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)