【问题标题】:Combine multiple routes into one serverless function in Vercel using Python?使用 Python 在 Vercel 中将多个路由组合成一个无服务器函数?
【发布时间】:2020-06-21 21:58:25
【问题描述】:

我目前有一个带有 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 路由中组合该路由以避免创建另一个无服务器功能。

【问题讨论】:

    标签: python flask next.js vercel sanic


    【解决方案1】:

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

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

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

    【讨论】:

    • Routing to "src": "/(.*)" 覆盖 Nextjs 路由,这不是人们想要做的。应该只路由到 /api 路由。我尝试将源更改为“src”:“/api/(.*)”,但这不起作用
    • 哦,是的,我应该把它包括在内。我的项目将 vercel 专门用于非 SSG 的功能,所以这适用于我的用例
    猜你喜欢
    • 2020-12-18
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 2018-11-16
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多