'How to deploy fastapi to google cloud run

I have a fastapi app that I want to deploy to google cloud run.

With a gRPC python project, We deploy it as

gcloud beta run deploy countries --source .

But this doesn't deploy as expected. I watched a video that deploying from source uses Google cloud buildpacks.

Is there anyone with a way of doing that?

My code is like


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()]

Appreciate your help



Solution 1:[1]

The solution to I've found is creating a 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

Then running

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

Then after image is submitted to gcloud, running

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

Solution 2:[2]

What error message do you see when you deploy with the buildpacks? When deploying Python apps, you need to include a Procfile in the root of your application that declares the command you should use to start the app:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cory
Solution 2 Matthew