AWS Lambda, API Gateway, ограничения и лучшие практики
Запуск FastAPI в serverless среде (AWS Lambda, Cloud Functions).
Serverless — выполнение кода без управления серверами. Провайдер управляет инфраструктурой, вы платите за время выполнения.
pip install mangumfrom fastapi import FastAPI
from mangum import Mangum
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
# Handler для Lambda
handler = Mangum(app)service: fastapi-app
provider:
name: aws
runtime: python3.11
region: us-east-1
memorySize: 256
timeout: 30
functions:
api:
handler: main.handler
events:
- http:
path: /
method: ANY
- http:
path: /{proxy+}
method: ANY
plugins:
- serverless-python-requirementsnpm install -g serverless
serverless plugin install -n serverless-python-requirements
serverless deployfrom fastapi import FastAPI
from functions_framework import http
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@http
def main(request):
from mangum import Mangum
asgi_handler = Mangum(app)
return asgi_handler(request.scope, request.receive)fastapi
mangum
functions-framework
gcloud functions deploy main \
--runtime python311 \
--trigger-http \
--allow-unauthenticated \
--entry-point mainimport azure.functions as func
from fastapi import FastAPI
from mangum import Mangum
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
asgi_app = Mangum(app)
def main(req: func.HttpRequest) -> func.HttpResponse:
return asgi_app(req.scope, req.receive)# requirements.txt только с необходимым
fastapi==0.104.1
mangum==0.17.0
pydantic==2.5.0functions:
api:
handler: main.handler
provisionedConcurrency: 5 # Держать 5 инстансов тёплыми# Ленивые импорты
def get_item(item_id: int):
from expensive_module import expensive_function
return expensive_function(item_id)functions:
api:
handler: main.handler
events:
- http:
path: /
method: ANY
cors: true
- http:
path: /{proxy+}
method: ANY
cors: truecustom:
customDomain:
domainName: api.example.com
basePath: ''
stage: ${self:provider.stage}
createRoute53Record: trueprovider:
environment:
DATABASE_URL: ${ssm:/prod/database-url}
SECRET_KEY: ${ssm:/prod/secret-key}docker run --rm -it -p 4566:4566 localstack/localstackserverless plugin install -n serverless-offline
serverless offlineprovider:
tracing:
apiGateway: true
lambda: truefunctions:
api:
handler: main.handler
tags:
Service: fastapi
Environment: prodВопросы ещё не добавлены
Вопросы для этой подтемы ещё не добавлены.