使用 Python 将多个路由合并到 Vercel 中的一个无服务器函数中?

Kal*_*tan 2 python sanic vercel

我目前有一个带有 python api 后端的 Nextjs 应用程序。我遇到的问题是 Vercel 有 24 个无服务器函数的限制,他们似乎建议应该结合无服务器函数来“优化”您的函数并避免冷启动。

目前我有以下代码

from sanic import Sanic
from sanic.response import json
app = Sanic()


@app.route('/')
@app.route('/<path:path>')
async def index(request, path=""):
    return json({'hello': path})

@app.route('/other_route')
async def other_route(request, path=""):
    return json({'whatever': path})
Run Code Online (Sandbox Code Playgroud)

然而,当我点击时,api/other_route我得到了 404。我知道我可以创建名为 But 的单独文件other_route.py,但我想知道是否有一种方法可以将该路由合并到我的index.py路由中,以避免创建另一个无服务器函数。

Sea*_*Aye 6

您需要在项目根目录中创建一个 vercel 配置vercel.json

{
    "routes": [{
        "src": "/api/(.*)",
        "dest": "api/index.py"
    }]
}
Run Code Online (Sandbox Code Playgroud)

这会将所有请求路由到/Sanic 实例。Sanic 然后知道如何路由到处理程序。您还应该将方法中的路径参数更改other_routepath="other_route"

  • 哦,是的,我应该把它包括在内。我的项目仅将 vercel 用于函数而不是 SSG,因此这适用于我的用例 (2认同)