簡體   English   中英

如何將fastapi部署到google cloud run

[英]How to deploy fastapi to google cloud run

我有一個要部署到 google cloud run 的 fastapi 應用程序。

使用 gRPC python 項目,我們將其部署為

gcloud beta run deploy countries --source .

但這並沒有按預期部署。 我觀看了一段使用Google 雲構建包從源代碼部署的視頻。

有沒有人有辦法做到這一點?

我的代碼就像


from typing import List
import geopandas as gpd
from fastapi import FastAPI
from geojson_pydantic.geometries import Geometry
from geojson_pydantic.features import Feature
from pydantic import BaseModel
from shapely.geometry.geo import shape
import json
import shapely

class Country(BaseModel):
    name: str
    code: str
    type: str
    geometry: Feature


app = FastAPI(
    title="Natural Earth Countries",
    description="This is a list of endpoints which you can use to access natural earth data.",
    version="0.0.1",
    docs_url='/',
)

gdf = gpd.read_file('data/ne_110m_admin_0_countries.zip')
gdf['name'] = gdf['ADMIN'].apply(lambda x: x.lower())

@app.get('/countries/all')
def get_all_countries() -> List[Country]:
    return rows_to_countries(gdf)


@app.get('/countries/search/{name}')
def search_countries(name: str):
    name = name.lower()
    subset = gdf.loc[gdf["name"].str.contains(name)]
    return rows_to_countries(subset)

@app.get('/countries/within-boundary')
def countries_intersecting(boundary: Geometry):
    bounds = shape(boundary)
    subset = gdf.loc[gdf.intersects(bounds)]
    return rows_to_countries(subset)


def row_to_country(row):
    return Country(
        name=row["ADMIN"],
        type=row["TYPE"],
        geometry=Feature(geometry=row['geometry']),
        code=row["ADM0_A3"],
    )


def rows_to_countries(gdf):
    return [row_to_country(row) for _, row in gdf.iterrows()]

感謝你的幫助

我發現的解決方案是創建一個 Dockerfile

FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8

COPY . /app
ENV APP_HOME /app

WORKDIR $APP_HOME
COPY . ./

RUN pip install -r requirements.txt

CMD exec gunicorn --bind :$PORT --workers 1 --worker-class uvicorn.workers.UvicornWorker  --threads 8 main:app

然后運行

gcloud builds submit --tag gcr.io/PROJECT-ID/countries_fastapi

然后將圖像提交到 gcloud 后,運行

gcloud run deploy --image gcr.io/bitnami-oyzgng8y5a/countries_fastapi --platform managed

嗨 - 我認為如果您想添加諸如數據庫遷移和其他 gcp 集成之類的內容https://github.com/anthcor/cloudrun-fastapi,這個 repo 可以提供幫助

使用 buildpack 部署時,您會看到什么錯誤消息? 部署 Python 應用程序時,您需要在應用程序的根目錄中包含一個Procfile ,它聲明了您應該用來啟動應用程序的命令:

web: gunicorn --bind :$PORT --workers 1 --worker-class uvicorn.workers.UvicornWorker  --threads 8 main:app

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM