跳到正文
Vercel Blog(vercel.com)· Daniel Park·· 7 天前精選AI 評分77

Vercel Routing Middleware 現已支援 Python

Routing Middleware now supports Python

AI 導讀

Vercel 宣佈 Routing Middleware 現已支援 Python,讓開發者能為 FastLab、Flask、Django 等框架編寫在請求到達應用程式之前執行的路由中介軟體。

推薦理由

原文提供 Python 路由中介軟體的設定方式與程式碼範例,開發者可據此評估如何整合至現有專案中。

正文 · 原文

You can now write routing middleware in Python for FastAPI, Flask, Django, and other Python frameworks. It runs before requests reach your app, and can rewrite, redirect, or answer them.

To set it up, point the proxy entrypoint in vercel.toml at your proxy:

vercel.toml

[proxy]

entrypoint = "proxy:proxy"

Your middleware is an ASGI or WSGI app that runs separately from your main app, with only the packages in the vercel.proxy dependency group of your pyproject.toml. Add the packages your middleware imports to that group:

uv add --group vercel.proxy vercel-proxy

The vercel-proxy package provides utilities for writing routing middleware on Vercel, including a Proxy app that routes requests by path:

proxy.py

from urllib.parse import quote

from vercel.proxy import ContinueResponse, Proxy, RedirectResponse, Request, Response

proxy = Proxy()

@proxy.route("/old-blog/{slug}")

def old_blog(request: Request) -> Response:

slug = quote(request.path_params["slug"])

return RedirectResponse(f"/blog/{slug}", status_code=308)

@proxy.route("/api/{path:path}")

def api(request: Request) -> Response:

return ContinueResponse(request_headers={"x-api-version": "2"})

Requests that match no route continue to your app unchanged.

For more information, see the Routing Middleware Python reference.

來源: Vercel Blog (vercel.com)
開啟原文