如何在 FastAPI 中没有路由装饰器的情况下功能性地将函数分配给路由?

How to assign a function to a route functionally, without a route decorator in FastAPI?

在 Flask 中,可以在功能上将任意函数分配给路由:

from flask import Flask
app = Flask()

def say_hello():
    return "Hello"

app.add_url_rule('/hello', 'say_hello', say_hello)

等于(带装饰器):

@app.route("/hello")
def say_hello():
    return "Hello"

FastAPI有这么简单实用的方法(add_url_rule)吗?

您可以使用 the add_api_route method 以编程方式将路由添加到路由器或应用程序:

from fastapi import FastAPI, APIRouter


def foo_it():
    return {'Fooed': True}


app = FastAPI()
router = APIRouter()
router.add_api_route('/foo', endpoint=foo_it)
app.include_router(router)
app.add_api_route('/foo-app', endpoint=foo_it)

两者都在两个不同的位置公开相同的端点:

λ curl http://localhost:8000/foo
{"Fooed":true}
λ curl http://localhost:8000/foo-app
{"Fooed":true}