Dou*_*ett 1 python buildpack gcloud google-cloud-run fastapi
我有一个 fastapi 应用程序,我想将其部署到 google cloud run。
对于 gRPC python 项目,我们将其部署为
gcloud beta run deploy countries --source .
Run Code Online (Sandbox Code Playgroud)
但这并没有按预期部署。我观看了一个使用Google cloud buildpacks从源代码部署的视频。
有没有人有办法做到这一点?
我的代码就像
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()]
Run Code Online (Sandbox Code Playgroud)
感谢你的帮助
我找到的解决方案是创建一个 Dockerfile
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8
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
Run Code Online (Sandbox Code Playgroud)
然后运行
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8
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
Run Code Online (Sandbox Code Playgroud)
然后将图像提交到gcloud后,运行
gcloud run deploy --image gcr.io/bitnami-oyzgng8y5a/countries_fastapi --platform managed
Run Code Online (Sandbox Code Playgroud)