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

md598:

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

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

url = ngrok.connect(port=8000)
print('Public URL:', url)
nest_asyncio.apply()
uvicorn.run(app, port=8000)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章