[ PROMPT_NODE_26840 ]
web-endpoints
[ SKILL_DOCUMENTATION ]
# Web 端点
## 快速开始
使用单个装饰器创建 Web 端点:
python
image = modal.Image.debian_slim().pip_install("fastapi[standard]")
@app.function(image=image)
@modal.fastapi_endpoint()
def hello():
return "Hello world!"
## 开发与部署
### 使用 `modal serve` 进行开发
bash
modal serve server.py
创建具有实时重载功能的临时应用。对端点的更改几乎会立即生效。
### 使用 `modal deploy` 进行部署
bash
modal deploy server.py
创建具有稳定 URL 的持久化端点。
## 简单端点
### 查询参数
python
@app.function(image=image)
@modal.fastapi_endpoint()
def square(x: int):
return {"square": x**2}
调用方式:
bash
curl "https://workspace--app-square.modal.run?x=42"
### POST 请求
python
@app.function(image=image)
@modal.fastapi_endpoint(method="POST")
def square(item: dict):
return {"square": item['x']**2}
调用方式:
bash
curl -X POST -H 'Content-Type: application/json'
--data '{"x": 42}'
https://workspace--app-square.modal.run
### Pydantic 模型
python
from pydantic import BaseModel
class Item(BaseModel):
name: str
qty: int = 42
@app.function()
@modal.fastapi_endpoint(method="POST")
def process(item: Item):
return {"processed": item.name, "quantity": item.qty}
## ASGI 应用 (FastAPI, Starlette, FastHTML)
托管完整的 ASGI 应用:
python
image = modal.Image.debian_slim().pip_install("fastapi[standard]")
@app.function(image=image)
@modal.concurrent(max_inputs=100)
@modal.asgi_app()
def fastapi_app():
from fastapi import FastAPI
web_app = FastAPI()
@web_app.get("/")
async def root():
return {"message": "Hello"}
@web_app.post("/echo")
async def echo(request: Request):
body = await request.json()
return body
return web_app
## WSGI 应用 (Flask, Django)
托管同步 Web 框架:
python
image = modal.Image.debian_slim().pip_install("flask")
@app.function(image=image)
@modal.concurrent(max_inputs=100)
@modal.wsgi_app()
def flask_app():
from flask import Flask, request
web_app = Flask(__name__)
@web_app.post("/echo")
def echo():
return request.json
return web_app
## 非 ASGI Web 服务器
针对具有自定义网络绑定的框架:
python
@app.function()
@modal.concurrent(max_inputs=100)
@modal.web_server(8000)
def my_server():
import subprocess
# 必须绑定 t