首页 > 解决方案 > 使用 Python 在 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})

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

标签: pythonflasknext.jsvercelsanic

解决方案


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

{
    "routes": [{
        "src": "/api/(.*)",
        "dest": "api/index.py"
    }]
}

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


推荐阅读