From e30ae3f6b86a04b450ec75533c85cc592bb1fd39 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sun, 29 Nov 2026 14:25:10 +0900 Subject: [PATCH] feat(run): add Flask and FastAPI run configurations (#6647) Flask and FastAPI apps could only run as ordinary scripts. Adds Flask server and FastAPI run configuration types: Flask runs python -m flask run with FLASK_APP / FLASK_DEBUG (read by every Flask version), host, port and extra options; FastAPI runs python -m uvicorn with reload, host, port and options. Both use the Python interpreter choice and debug with debugpy; under the debugger Flask runs with --no-debugger, and without subprocess attach the reloader is turned off so breakpoints still stop. A top-level (or src/) app.py, wsgi.py, main.py or app/main.py assigning Flask(...) or FastAPI(...) to a module-level name gets a detected configuration. The list of Python run kinds is now one function (ide_run::is_python_kind) instead of copies in the host, Docker, process and SDK code. Closes #6532 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/ops/run.rs | 2 +- crates/ide-remote/src/docker.rs | 4 +- crates/ide-run/src/detect.rs | 47 +++++ crates/ide-run/src/lib.rs | 6 + crates/ide-run/src/process.rs | 4 +- crates/ide-run/tests/detect.rs | 43 ++++ crates/ide-sdk/src/apply.rs | 10 +- docs/en/guide/run.mdx | 3 +- docs/en/languages/python.mdx | 10 +- docs/zh/guide/run.mdx | 3 +- docs/zh/languages/python.mdx | 10 +- .../debugger/__tests__/launch.test.ts | 27 +++ src/features/debugger/launch.ts | 10 + src/features/run/context.ts | 2 +- src/features/run/pythonWebTypes.ts | 189 ++++++++++++++++++ src/features/run/runConfigTypes.test.tsx | 107 ++++++++++ src/features/run/types.ts | 13 ++ src/platform/i18n.test.ts | 3 + src/platform/locales/text/en.json | 16 +- src/platform/locales/text/zh.json | 16 +- src/workbench/contributions.ts | 11 +- 21 files changed, 513 insertions(+), 23 deletions(-) create mode 100644 src/features/run/pythonWebTypes.ts diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 4409f59e4..627eec618 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -512,7 +512,7 @@ async fn start_inner( } // A Python configuration pointing at a missing interpreter fails in the depth of // process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK". - let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test"); + let is_python = ide_run::is_python_kind(&config.kind); if is_python && Path::new(&config.command).components().count() > 1 { let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new(""))); let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command)); diff --git a/crates/ide-remote/src/docker.rs b/crates/ide-remote/src/docker.rs index a27f0bcbd..f43513703 100644 --- a/crates/ide-remote/src/docker.rs +++ b/crates/ide-remote/src/docker.rs @@ -185,9 +185,7 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult = run.file_env.clone(); - if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test") - && !command.env.contains_key("PYTHONUNBUFFERED") - { + if ide_run::is_python_kind(&config.kind) && !command.env.contains_key("PYTHONUNBUFFERED") { env.insert("PYTHONUNBUFFERED".into(), "1".into()); } env.extend(command.env.clone()); diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs index c04934396..a60b306fc 100644 --- a/crates/ide-run/src/detect.rs +++ b/crates/ide-run/src/detect.rs @@ -1220,6 +1220,20 @@ fn py_config( c.debug("debugpy") } +/// The variable a module-level `name = Flask(...)` / `name = FastAPI(...)` assigns, if any. +fn web_app(text: &str, class: &str) -> Option { + text.lines().find_map(|line| { + let (var, value) = line.split_once('=')?; + let var = var.trim_end().split(':').next()?.trim_end(); + let value = value.trim_start(); + // `Flask(…)` or `flask.Flask(…)`. + let value = value.strip_prefix(&format!("{}.", class.to_lowercase())).unwrap_or(value); + let call = value.strip_prefix(class)?.trim_start(); + let ident = !var.is_empty() && var.chars().all(|c| c.is_alphanumeric() || c == '_'); + (ident && call.starts_with('(')).then(|| var.to_owned()) + }) +} + fn uses_pytest(root: &Path) -> bool { if ["pytest.ini", "tox.ini", "conftest.py"].iter().any(|f| root.join(f).is_file()) { return true; @@ -1285,6 +1299,39 @@ fn detect_python(top: &Path, root: &Path, out: &mut Vec) { &["manage.py", "runserver"], )); } + // `src/main.py` runs as `main` with `src` on the path (uvicorn `--app-dir`, a file path for `FLASK_APP`). + let apps = [("app.py", "app"), ("wsgi.py", "wsgi"), ("main.py", "main"), ("app/main.py", "app.main")]; + for (dir, (file, module)) in ["", "src/"].into_iter().flat_map(|dir| apps.map(|app| (dir, app))) { + let Some(text) = read(&root.join(format!("{dir}{file}"))) else { continue }; + if let Some(var) = web_app(&text, "FastAPI") { + let app = format!("{module}:{var}"); + let mut args = vec!["-m", "uvicorn", &app, "--reload"]; + if !dir.is_empty() { + args.extend(["--app-dir", "src"]); + } + out.push(py_config( + format!("fastapi:{dir}{app}"), + format!("uvicorn {app}"), + "fastapi", + env.python(), + &args, + )); + } else if let Some(var) = web_app(&text, "Flask") { + // `FLASK_APP` / `FLASK_DEBUG`, which every Flask reads (`--app` / `--debug` need 2.2). + let target = if dir.is_empty() { module.to_owned() } else { format!("{dir}{file}") }; + let app = if var == "app" { target } else { format!("{target}:{var}") }; + let mut c = py_config( + format!("flask:{app}"), + format!("flask run ({app})"), + "flask", + env.python(), + &["-m", "flask", "run"], + ); + c.env.insert("FLASK_APP".into(), app); + c.env.insert("FLASK_DEBUG".into(), "1".into()); + out.push(c); + } + } let mut modules = Vec::new(); for base in [root.to_path_buf(), root.join("src")] { for dir in ide_core::project_roots::children(&base) { diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index e1a7baddc..ed1c39b23 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -266,6 +266,12 @@ pub struct RunAttach { pub use external::{EXTERNAL_PREFIX, ExternalDetection, set_external_detection}; +/// Kinds whose command is a Python interpreter (or a runner of one): they get the project +/// interpreter, `PYTHONUNBUFFERED` and the interpreter paths on `PYTHONPATH`. +pub fn is_python_kind(kind: &str) -> bool { + matches!(kind, "python" | "pytest" | "unittest" | "doctest" | "django-test" | "flask" | "fastapi") +} + /// Detects configs from package.json scripts, Cargo.toml targets, build.gradle(.kts), /// pom.xml, go.mod, pyproject/pytest, Makefile. pub fn detect(root: &Path) -> Vec { diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rs index 03de15bb7..3ef3a8e91 100644 --- a/crates/ide-run/src/process.rs +++ b/crates/ide-run/src/process.rs @@ -434,7 +434,7 @@ impl ProcessManager { return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal")); } let mut env = launch_env(root, config)?; - if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test") { + if crate::is_python_kind(&config.kind) { crate::python_path::extend(&mut env.vars, &options.python_paths, !env.clear)?; if let Some(prefix) = &options.conda_prefix { let user_set = |key: &str| config.env.contains_key(key); @@ -1124,7 +1124,7 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult { let paths: Vec = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect(); crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))? }; - if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test") + if crate::is_python_kind(&config.kind) && !config.env.contains_key("PYTHONUNBUFFERED") && !vars.contains_key("PYTHONUNBUFFERED") { diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/detect.rs index 1e9f1a586..8160bf3a7 100644 --- a/crates/ide-run/tests/detect.rs +++ b/crates/ide-run/tests/detect.rs @@ -676,6 +676,49 @@ fn python_projects() { assert_eq!(ids(&c), ["python:module:app"]); } +#[test] +fn flask_and_fastapi_apps() { + let python = if cfg!(windows) { "python" } else { "python3" }; + let dir = + project(&[("requirements.txt", "flask\n"), ("app.py", "from flask import Flask\n\napp = Flask(__name__)\n")]); + let c = detect(dir.path()); + let flask = find(&c, "flask:app"); + // `FLASK_APP` / `FLASK_DEBUG` rather than `--app` / `--debug`, which Flask before 2.2 rejects. + assert_eq!(cmdline(flask), format!("{python} -m flask run")); + assert_eq!(flask.env.get("FLASK_APP").map(String::as_str), Some("app")); + assert_eq!(flask.env.get("FLASK_DEBUG").map(String::as_str), Some("1")); + assert_eq!(flask.kind, "flask"); + assert_eq!(flask.debug_adapter.as_deref(), Some("debugpy")); + + // `flask.Flask(…)` and a src layout. + let dir = project(&[("requirements.txt", ""), ("src/main.py", "import flask\nserver = flask.Flask(__name__)\n")]); + let c = detect(dir.path()); + let flask = find(&c, "flask:src/main.py:server"); + assert_eq!(flask.env.get("FLASK_APP").map(String::as_str), Some("src/main.py:server")); + let dir = project(&[("requirements.txt", ""), ("src/main.py", "import fastapi\napp = fastapi.FastAPI()\n")]); + let c = detect(dir.path()); + let api = find(&c, "fastapi:src/main:app"); + assert_eq!(cmdline(api), format!("{python} -m uvicorn main:app --reload --app-dir src")); + + let dir = project(&[ + ("pyproject.toml", "[project]\nname = 'api'\n"), + ("uv.lock", ""), + ("app/main.py", "from fastapi import FastAPI\n\napi: FastAPI = FastAPI(title='x')\n"), + ]); + let c = detect(dir.path()); + let api = find(&c, "fastapi:app.main:api"); + assert_eq!(cmdline(api), "uv run python -m uvicorn app.main:api --reload"); + assert_eq!(api.kind, "fastapi"); + + // An app made inside a factory, or a module that only imports Flask, is left to the user. + let dir = project(&[ + ("requirements.txt", ""), + ("app.py", "from flask import Flask\n\ndef create_app():\n app = Flask(__name__)\n return app\n"), + ("main.py", "import flask\nFlaskApp = 1\n"), + ]); + assert!(detect(dir.path()).iter().all(|c| c.kind != "flask")); +} + #[test] fn python_unittest_projects() { const UNITTEST: &str = "import unittest\n\nclass T(unittest.TestCase):\n pass\n"; diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rs index 11ecfa05c..4b1ae5201 100644 --- a/crates/ide-sdk/src/apply.rs +++ b/crates/ide-sdk/src/apply.rs @@ -1993,8 +1993,7 @@ pub fn run_target<'a>(config: &RunConfig, settings: &'a Settings) -> Option<&'a } fn is_python_config(config: &RunConfig, program: &str) -> bool { - matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test") - || is_python_command(program) + ide_run::is_python_kind(&config.kind) || is_python_command(program) } /// Whether the configuration's `JAVA_HOME` is the one Settings choose (the Maven runner JRE, @@ -2107,7 +2106,7 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback: resolve_run_command(c, root, s); let mut path_dirs: Vec = Vec::new(); match c.kind.as_str() { - "python" | "pytest" | "unittest" | "doctest" | "django-test" => { + kind if ide_run::is_python_kind(kind) => { let command = Path::new(&c.command); let own = !c.detected && command.components().count() > 1 && is_python_command(&c.command); let python = if own { @@ -2125,10 +2124,7 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback: let runner_options = runner && c.args.first().map(String::as_str) == Some("run") && c.args.get(1).is_some_and(|a| a.starts_with('-')); - if matches!(c.kind.as_str(), "python" | "unittest" | "doctest" | "django-test") - && !runner_options - && (runner || is_python_command(&c.command)) - { + if c.kind != "pytest" && !runner_options && (runner || is_python_command(&c.command)) { if runner && c.args.first().map(String::as_str) == Some("run") { // `uv run python …` → ` …` let skip = if c.args.get(1).is_some_and(|a| is_python_command(a)) { 2 } else { 1 }; diff --git a/docs/en/guide/run.mdx b/docs/en/guide/run.mdx index be5210290..a989d0157 100644 --- a/docs/en/guide/run.mdx +++ b/docs/en/guide/run.mdx @@ -24,7 +24,7 @@ When a project opens, OpenIDEA scans its build files (also in nested projects of | `Cargo.toml` | `cargo run` for each binary, `cargo test`, `cargo build`; workspace members are included | | `build.gradle(.kts)` / `pom.xml` | Gradle and Maven run configurations | | `go.mod` / `go.work` | Go programs and tests | -| `pyproject.toml`, `setup.py`, `requirements.txt`, `pytest.ini`, `tox.ini`, `manage.py`, a `.venv` | Python programs, pytest, Django | +| `pyproject.toml`, `setup.py`, `requirements.txt`, `pytest.ini`, `tox.ini`, `manage.py`, a `.venv` | Python programs, pytest, Django, Flask and FastAPI apps | | `composer.json`, `phpunit.xml` | PHPUnit | | Ruby projects (`Gemfile`, `Rakefile`, …) | Rake tasks, RSpec, Minitest | | `CMakeLists.txt` | CMake build and run targets | @@ -101,6 +101,7 @@ Open **Run › Edit Configurations…** (also in the run widget menu). The **Run | **Tomcat Server** | A WAR application in a local Tomcat | | **Python** | A Python script or `-m` module | | **pytest** / **Django tests** | pytest tests, `manage.py test` | +| **Flask server** / **FastAPI** | `flask run`, `uvicorn module:app` | | **Ruby** / **Rake** / **RSpec** | A Ruby script, a Rake task, RSpec examples | | **PHPUnit** | PHPUnit tests | | **Go Build** / **Go Test** | A Go application, Go tests | diff --git a/docs/en/languages/python.mdx b/docs/en/languages/python.mdx index 535304425..aaa953fdb 100644 --- a/docs/en/languages/python.mdx +++ b/docs/en/languages/python.mdx @@ -169,7 +169,15 @@ See [Debugging](/en/guide/debugging) for breakpoints, stepping and the debugger ## Framework support -Django is the only framework with dedicated support: the `manage.py runserver` and `manage.py test` configurations, the **Django tests** configuration type (target, settings module, options), running single `TestCase` tests from the gutter, and Django mode in the debugger. Other frameworks (Flask, FastAPI and so on) run as ordinary scripts or console scripts. +Django has the `manage.py runserver` and `manage.py test` configurations, the **Django tests** configuration type (target, settings module, options), running single `TestCase` tests from the gutter, and Django mode in the debugger. Other frameworks run as ordinary scripts or console scripts, except Flask and FastAPI below. + +### Flask and FastAPI + +The **Flask server** configuration runs `python -m flask run` with `FLASK_APP` and `FLASK_DEBUG` set, which every Flask version reads: **Application** is the `FLASK_APP` value (a module or file, optionally with the app or factory, `hello:create_app()`; empty finds `app.py` or `wsgi.py`), **Debug mode** sets `FLASK_DEBUG=1` (reloader and the in-browser debugger), and **Host**, **Port** and **Additional options** go to `flask run`. The **FastAPI** configuration runs `python -m uvicorn ` with **Reload on code changes** (`--reload`), **Host**, **Port** and further uvicorn options. Both use the Interpreter choice of Python configurations and debug with debugpy; Jinja2 template breakpoints work under Flask. + +Under the debugger, Flask runs with `--no-debugger`, so exceptions reach debugpy instead of the in-browser debugger. With a reloader, requests are served by a child process: breakpoints stop there while **Attach to subprocess automatically while debugging** is on (the default, under **Settings › Build, Execution, Deployment › Python Debugger**); with it off, debugging runs without the reloader (`--no-reload`, no `--reload`). + +A top-level `app.py`, `wsgi.py` or `main.py`, or `app/main.py`, also under `src/`, that assigns `Flask(...)` or `FastAPI(...)` (or `flask.Flask(...)`, `fastapi.FastAPI(...)`) to a module-level name gets one of these configurations detected (`flask run` with `FLASK_APP=app`, `uvicorn app.main:app --reload`). An app created inside a factory function is not detected; add the configuration by hand. Detection doesn't check that Flask or uvicorn is installed. ### Django templates diff --git a/docs/zh/guide/run.mdx b/docs/zh/guide/run.mdx index 4bc6154d7..a0377a941 100644 --- a/docs/zh/guide/run.mdx +++ b/docs/zh/guide/run.mdx @@ -24,7 +24,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码, | `Cargo.toml` | 每个二进制一个 `cargo run`,以及 `cargo test`、`cargo build`;包含 workspace 成员 | | `build.gradle(.kts)` / `pom.xml` | Gradle、Maven 运行配置 | | `go.mod` / `go.work` | Go 程序和测试 | -| `pyproject.toml`、`setup.py`、`requirements.txt`、`pytest.ini`、`tox.ini`、`manage.py`、`.venv` | Python 程序、pytest、Django | +| `pyproject.toml`、`setup.py`、`requirements.txt`、`pytest.ini`、`tox.ini`、`manage.py`、`.venv` | Python 程序、pytest、Django、Flask 和 FastAPI 应用 | | `composer.json`、`phpunit.xml` | PHPUnit | | Ruby 项目(`Gemfile`、`Rakefile` 等) | Rake task、RSpec、Minitest | | `CMakeLists.txt` | CMake 构建和运行目标 | @@ -97,6 +97,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码, | **Tomcat 服务器** | 在本地 Tomcat 里运行 WAR 应用 | | **Python** | Python 脚本或 `-m` 模块 | | **pytest** / **Django 测试** | pytest 测试、`manage.py test` | +| **Flask 服务器** / **FastAPI** | `flask run`、`uvicorn module:app` | | **Ruby 语言** / **Rake 任务** / **RSpec 测试** | Ruby 脚本、Rake 任务、RSpec 用例 | | **PHPUnit** | PHPUnit 测试 | | **Go 构建** / **Go 测试** | Go 应用、Go 测试 | diff --git a/docs/zh/languages/python.mdx b/docs/zh/languages/python.mdx index bcd0a874e..ab0b30e1c 100644 --- a/docs/zh/languages/python.mdx +++ b/docs/zh/languages/python.mdx @@ -169,7 +169,15 @@ Python 调试使用 debugpy。开始调试时如果缺少 debugpy,OpenIDEA 会 ## 框架支持 -目前只有 Django 有专门支持:`manage.py runserver` 和 `manage.py test` 运行配置、**Django 测试** 配置类型(目标、settings 模块、选项)、在左侧栏运行单个 `TestCase` 测试,以及调试器的 Django 模式。Flask、FastAPI 等其他框架按普通脚本或命令行入口运行。 +Django 有 `manage.py runserver` 和 `manage.py test` 运行配置、**Django 测试** 配置类型(目标、settings 模块、选项)、在左侧栏运行单个 `TestCase` 测试,以及调试器的 Django 模式。除下文的 Flask 和 FastAPI 外,其他框架按普通脚本或命令行入口运行。 + +### Flask 和 FastAPI + +**Flask 服务器** 配置运行 `python -m flask run`,并设置所有 Flask 版本都能识别的 `FLASK_APP` 和 `FLASK_DEBUG`:**应用程序** 即 `FLASK_APP` 的值(模块或文件,可附带应用或工厂函数,如 `hello:create_app()`;留空时查找 `app.py` 或 `wsgi.py`),**调试模式** 设置 `FLASK_DEBUG=1`(自动重新加载和浏览器内调试器),**主机**、**端口** 和 **附加选项** 传给 `flask run`。**FastAPI** 配置运行 `python -m uvicorn `,可设 **代码变更时重新加载**(`--reload`)、**主机**、**端口** 和其他 uvicorn 选项。两者都使用 Python 配置的解释器选择,并用 debugpy 调试;在 Flask 下 Jinja2 模板断点可用。 + +在调试器下,Flask 以 `--no-debugger` 运行,异常交给 debugpy 而不是浏览器内调试器。启用自动重新加载时,请求由子进程处理:**调试时自动附加到子进程**(默认开启,位于 **设置 › 构建、执行、部署 › Python 调试器**)开启时断点在子进程中生效;关闭时调试会去掉自动重新加载(`--no-reload`,不加 `--reload`)。 + +顶层(或 `src/` 下)的 `app.py`、`wsgi.py`、`main.py` 或 `app/main.py` 若把 `Flask(...)` 或 `FastAPI(...)`(或 `flask.Flask(...)`、`fastapi.FastAPI(...)`)赋给模块级变量,会自动检测出对应配置(`FLASK_APP=app` 的 `flask run`、`uvicorn app.main:app --reload`)。在工厂函数里创建的应用不会被检测到,需要手动添加配置。检测不会检查 Flask 或 uvicorn 是否已安装。 ### Django 模板 diff --git a/src/features/debugger/__tests__/launch.test.ts b/src/features/debugger/__tests__/launch.test.ts index d169fe708..587efd2ff 100644 --- a/src/features/debugger/__tests__/launch.test.ts +++ b/src/features/debugger/__tests__/launch.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { RunConfig } from "@/platform/ipc"; import { usePlatform } from "@/platform/platformInfo"; +import { useProject } from "@/platform/project"; import { useFlutterDevices } from "@/workbench/flutterDevices"; import { isJinjaTemplate } from "../breakpoints/languages"; import { debugUnsupportedReason, launchConfigFor, withEnvFiles } from "../launch"; @@ -249,6 +250,32 @@ describe("run config → launch config", () => { expect(asgi.jinja).toBeUndefined(); }); + it("debugpy: Flask without the in-browser debugger, and no reloader unless subprocesses are attached", () => { + const debug = (kind: string, args: string[]) => + launchConfigFor(rc({ kind, command: "python3", args, debugAdapter: "debugpy" }), "/p")!.args; + expect(debug("flask", ["-m", "flask", "run", "--port", "5001"])).toEqual([ + "run", + "--no-debugger", + "--port", + "5001", + ]); + expect(debug("python", ["-m", "flask", "--app", "app", "run", "--no-debugger"])).toEqual([ + "--app", + "app", + "run", + "--no-debugger", + ]); + expect(debug("fastapi", ["-m", "uvicorn", "main:app", "--reload"])).toEqual(["main:app", "--reload"]); + const settings = useProject.getState().settings; + try { + useProject.setState({ settings: { ...settings, debugger: { python: { attachSubprocess: false } } } as never }); + expect(debug("flask", ["-m", "flask", "run"])).toEqual(["run", "--no-debugger", "--no-reload"]); + expect(debug("fastapi", ["-m", "uvicorn", "main:app", "--reload"])).toEqual(["main:app"]); + } finally { + useProject.setState({ settings }); + } + }); + it("Jinja2 templates: their extensions anywhere, markup or text in a templates folder", () => { for (const p of [ "/p/mail/welcome.j2", diff --git a/src/features/debugger/launch.ts b/src/features/debugger/launch.ts index 7020da20d..bf5dc34f9 100644 --- a/src/features/debugger/launch.ts +++ b/src/features/debugger/launch.ts @@ -163,6 +163,16 @@ function debugpyLaunch(rc: RunConfig, cwd: string, templates: TemplateBreakpoint out.args = args.slice(1); if (args[0].endsWith("manage.py")) extra.django = true; } + // Werkzeug's in-browser debugger would catch exceptions before debugpy does. A reloader serves requests from + // a child process, which stops at breakpoints only when subprocesses are attached: without that, no reload. + const served = out.args ?? []; + const run = served.indexOf("run"); + if (extra.module === "flask" && run >= 0) { + const off = ["--no-debugger", ...(dbg.python.attachSubprocess ? [] : ["--no-reload"])]; + out.args = [...served.slice(0, run + 1), ...off.filter((a) => !served.includes(a)), ...served.slice(run + 1)]; + } else if (extra.module === "uvicorn" && !dbg.python.attachSubprocess) { + out.args = served.filter((a) => a !== "--reload"); + } // A Django Template's breakpoint needs `django` however Django starts (uvicorn, gunicorn, pytest-django). if (extra.module === "django" || templates.django) extra.django = true; // Jinja2 templates' breakpoints: Flask, or one already in a template (`python app.py`). Not on for every diff --git a/src/features/run/context.ts b/src/features/run/context.ts index a57307333..bc544c81f 100644 --- a/src/features/run/context.ts +++ b/src/features/run/context.ts @@ -159,7 +159,7 @@ export function projectPython(configs: RunConfig[], relPath?: string): { command } /** Kinds of a Python project's configurations. */ -export const PYTHON_KINDS = ["python", "pytest", "unittest", "doctest", "django-test"]; +export const PYTHON_KINDS = ["python", "pytest", "unittest", "doctest", "django-test", "flask", "fastapi"]; /** Settings › Python › Testing › Default test runner. */ export function pythonTestRunner(): PythonTestRunner { diff --git a/src/features/run/pythonWebTypes.ts b/src/features/run/pythonWebTypes.ts new file mode 100644 index 000000000..e0c6c76a6 --- /dev/null +++ b/src/features/run/pythonWebTypes.ts @@ -0,0 +1,189 @@ +/** + * PyCharm's "Flask server" and "FastAPI" configurations: `python -m flask run` with `FLASK_APP` / + * `FLASK_DEBUG` (which every Flask version reads; `--app` and `--debug` need Flask 2.2) and + * `python -m uvicorn `, with host, port and the development server's reloader. + */ +import type { RunConfig } from "@/platform/ipc"; +import type { RunConfigTypeContribution, RunConfigTypeField } from "@/workbench/contributions"; +import { formatArgs, parseArgs } from "./configs"; +import { isWindows } from "./jvmTypes"; +import { customCommandVisible, interpreterField, systemPython } from "./pythonTypes"; + +const interpreterFields: readonly RunConfigTypeField[] = [ + interpreterField, + { + key: "command", + label: "Command", + mono: true, + placeholder: "python3", + required: true, + hint: "e.g. python3, .venv/bin/python, uv, poetry", + visible: customCommandVisible, + }, + { + key: "runnerArgs", + label: "Runner arguments", + mono: true, + placeholder: "run python", + hint: "e.g. `run python` for uv/poetry; empty calls the interpreter itself", + }, +]; + +const serverFields = (port: string): RunConfigTypeField[] => [ + { key: "host", label: "Host", mono: true, placeholder: "127.0.0.1" }, + { key: "port", label: "Port", mono: true, placeholder: port }, +]; + +const flag = (on: string | undefined, name: string) => (on === "true" ? [name] : []); +const args = (text: string | undefined) => parseArgs(text ?? "", isWindows()); +const option = (value: string | undefined, name: string) => (value?.trim() ? [name, value.trim()] : []); + +/** `args` from `-m ` on: the runner args before it and the module's own arguments; null without it. */ +function moduleArgs(c: RunConfig, module: string): { runnerArgs: string; rest: string[] } | null { + const at = c.args.findIndex((a, i) => a === "-m" && c.args[i + 1] === module); + if (at < 0) return null; + return { runnerArgs: formatArgs(c.args.slice(0, at)), rest: c.args.slice(at + 2) }; +} + +/** Takes `--host` / `--port` (and their `=` forms; `-h` / `-p` for `flask run`, where `-h` is not help) out of `args`. */ +function takeServerOptions(args: string[], short: boolean): { host: string; port: string; rest: string[] } { + const out = { host: "", port: "", rest: [] as string[] }; + for (let i = 0; i < args.length; i++) { + const m = (short ? /^(--host|--port|-h|-p)(?:=(.*))?$/ : /^(--host|--port)(?:=(.*))?$/).exec(args[i]!); + const key = m && (m[1] === "--host" || m[1] === "-h" ? "host" : "port"); + if (!m || !key || (m[2] === undefined && args[i + 1] === undefined)) out.rest.push(args[i]!); + else out[key] = m[2] ?? args[++i]!; + } + return out; +} + +export const flaskType: RunConfigTypeContribution = { + id: "flask", + label: "Flask server", + icon: "file-python", + description: "Run a Flask application with flask run", + get defaults() { + return { command: systemPython(), debug: "true" }; + }, + debugAdapter: "debugpy", + fields: [ + ...interpreterFields, + { + key: "app", + label: "Application", + mono: true, + placeholder: "app", + hint: "Set as FLASK_APP: a module or file, optionally with the app or factory (hello:create_app()); empty finds app.py or wsgi.py", + }, + { + key: "debug", + label: "Debug mode", + control: "checkbox", + hint: "FLASK_DEBUG=1: reload on code changes and show the interactive debugger in the browser", + }, + ...serverFields("5000"), + { + key: "options", + label: "Additional options", + mono: true, + placeholder: "e.g. --cert adhoc --extra-files config.toml", + }, + ], + commandLine(p) { + return { + command: p.command?.trim() || systemPython(), + args: [ + ...args(p.runnerArgs), + "-m", + "flask", + "run", + ...option(p.host, "--host"), + ...option(p.port, "--port"), + ...args(p.options), + ], + setEnv: { FLASK_APP: p.app?.trim() || null, FLASK_DEBUG: p.debug === "true" ? "1" : null }, + }; + }, + paramsFrom(c) { + if (c.kind !== "flask") return null; + const found = moduleArgs(c, "flask"); + const run = found?.rest.indexOf("run") ?? -1; + if (!found || run < 0) return null; + // Options of the `flask` group (`--app`, `--env-file`) go before `run` and have no field. + if (run > 0) return null; + const { host, port, rest } = takeServerOptions(found.rest.slice(run + 1), true); + return { + command: c.command, + runnerArgs: found.runnerArgs, + app: c.env.FLASK_APP ?? "", + ...(/^(1|true|yes|on)$/i.test(c.env.FLASK_DEBUG ?? "") ? { debug: "true" } : {}), + host, + port, + options: formatArgs(rest), + }; + }, +}; + +export const fastapiType: RunConfigTypeContribution = { + id: "fastapi", + label: "FastAPI", + icon: "file-python", + description: "Run a FastAPI application with uvicorn", + get defaults() { + return { command: systemPython(), app: "main:app", reload: "true" }; + }, + debugAdapter: "debugpy", + fields: [ + ...interpreterFields, + { + key: "app", + label: "Application", + mono: true, + required: true, + placeholder: "main:app", + hint: "The module and the FastAPI instance in it, module:attribute", + }, + { + key: "reload", + label: "Reload on code changes", + control: "checkbox", + hint: "uvicorn --reload. Debugging stops at breakpoints in the reloaded process while Attach to subprocess automatically while debugging is on (the default); with it off, debugging runs without the reloader", + }, + ...serverFields("8000"), + { key: "options", label: "Additional options", mono: true, placeholder: "e.g. --reload-dir app --log-level debug" }, + ], + commandLine(p) { + return { + command: p.command?.trim() || systemPython(), + args: [ + ...args(p.runnerArgs), + "-m", + "uvicorn", + ...(p.app?.trim() ? [p.app.trim()] : []), + ...flag(p.reload, "--reload"), + ...option(p.host, "--host"), + ...option(p.port, "--port"), + ...args(p.options), + ], + }; + }, + paramsFrom(c) { + if (c.kind !== "fastapi") return null; + const found = moduleArgs(c, "uvicorn"); + if (!found) return null; + const [app = "", ...after] = found.rest[0]?.startsWith("-") ? ["", ...found.rest] : found.rest; + const { host, port, rest } = takeServerOptions( + after.filter((a) => a !== "--reload"), + false, + ); + return { + command: c.command, + runnerArgs: found.runnerArgs, + app, + ...(after.includes("--reload") ? { reload: "true" } : {}), + host, + port, + options: formatArgs(rest), + }; + }, +}; diff --git a/src/features/run/runConfigTypes.test.tsx b/src/features/run/runConfigTypes.test.tsx index 71e8e96ba..3ab732d77 100644 --- a/src/features/run/runConfigTypes.test.tsx +++ b/src/features/run/runConfigTypes.test.tsx @@ -1,6 +1,7 @@ import { useBuildModel } from "@/platform/buildModel"; import { useBuildPresentation } from "@/platform/projectPresentation"; import { useProject } from "@/platform/project"; +import { usePlatform } from "@/platform/platformInfo"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { fireEvent, render, screen } from "@testing-library/react"; import { registerActions } from "@/platform/actions"; @@ -514,6 +515,112 @@ describe("configuration types", () => { ).toBeNull(); }); + it("Flask and FastAPI round-trip commandLine / paramsFrom", () => { + const flask = typeFor("flask")!; + const fastapi = typeFor("fastapi")!; + // FLASK_APP / FLASK_DEBUG, which every Flask reads; `--app` and `--debug` need Flask 2.2. + expect(newConfigOfType(flask, [])).toMatchObject({ + kind: "flask", + command: "python3", + args: ["-m", "flask", "run"], + env: { FLASK_DEBUG: "1" }, + debugAdapter: "debugpy", + }); + expect(newConfigOfType(fastapi, [])).toMatchObject({ + kind: "fastapi", + args: ["-m", "uvicorn", "main:app", "--reload"], + debugAdapter: "debugpy", + }); + const cases: Array<{ + kind: string; + command: string; + args: string[]; + env?: Record; + params: Record; + }> = [ + { + kind: "flask", + command: "python3", + args: ["-m", "flask", "run"], + env: { FLASK_APP: "app", FLASK_DEBUG: "1" }, + params: { command: "python3", runnerArgs: "", app: "app", debug: "true", host: "", port: "", options: "" }, + }, + { + kind: "flask", + command: "uv", + args: ["run", "python", "-m", "flask", "run", "--host", "0.0.0.0", "--port", "8080", "--cert", "adhoc"], + env: { FLASK_APP: "hello:create_app()" }, + params: { + command: "uv", + runnerArgs: "run python", + app: "hello:create_app()", + host: "0.0.0.0", + port: "8080", + options: "--cert adhoc", + }, + }, + { + kind: "fastapi", + command: ".venv/bin/python", + args: ["-m", "uvicorn", "app.main:api", "--reload", "--port", "8001", "--log-level", "debug"], + params: { + command: ".venv/bin/python", + runnerArgs: "", + app: "app.main:api", + reload: "true", + host: "", + port: "8001", + options: "--log-level debug", + }, + }, + ]; + for (const { kind, command, args, env = {}, params } of cases) { + const type = kind === "flask" ? flask : fastapi; + const c = cfg(kind, { kind, command, args, env: { PATH: "/bin", ...env }, detected: true }); + expect(type.paramsFrom!(c)).toEqual(params); + expect(type.commandLine(params)).toMatchObject({ command, args }); + // Saved from the form, the variables the fields set follow them; others stay. + expect(withParams(c, params).env).toEqual({ PATH: "/bin", ...env }); + } + // Clearing a field removes its variable. + const app = cfg("f", { kind: "flask", command: "python3", args: ["-m", "flask", "run"], env: { FLASK_APP: "a" } }); + expect(withParams(app, { command: "python3", app: "" }).env).toEqual({}); + // `-h` is `flask run`'s host, but uvicorn's help; `--port=…` is read too. + expect( + flask.paramsFrom!(cfg("f", { kind: "flask", command: "python3", args: ["-m", "flask", "run", "-h", "0.0.0.0"] })), + ).toMatchObject({ host: "0.0.0.0", options: "" }); + expect( + fastapi.paramsFrom!(cfg("u", { kind: "fastapi", command: "python3", args: ["-m", "uvicorn", "m:a", "-h"] })), + ).toMatchObject({ host: "", options: "-h" }); + expect( + flask.paramsFrom!(cfg("f", { kind: "flask", command: "python3", args: ["-m", "flask", "run", "--port=5001"] })), + ).toMatchObject({ port: "5001", options: "" }); + // An option of the `flask` group (`--app`, `--env-file`) has no field: edited as a plain command. + for (const group of [ + ["--app", "app"], + ["--env-file", ".env"], + ]) + expect( + flask.paramsFrom!(cfg("f", { kind: "flask", command: "python3", args: ["-m", "flask", ...group, "run"] })), + ).toBeNull(); + }); + + it("parses Windows paths in the options on Windows", () => { + const os = usePlatform.getState().os; + usePlatform.setState({ os: "windows" } as never); + try { + expect(typeFor("fastapi")!.commandLine({ app: "m:a", options: "--reload-dir C:\\proj\\app" })!.args).toEqual([ + "-m", + "uvicorn", + "m:a", + "--reload-dir", + "C:\\proj\\app", + ]); + } finally { + usePlatform.setState({ os } as never); + } + }); + it("pytest round-trips commandLine / paramsFrom and opens implicit context configs in the form", () => { const pytest = typeFor("pytest")!; expect(pytest.debugAdapter).toBe("debugpy"); diff --git a/src/features/run/types.ts b/src/features/run/types.ts index 063e0ab0d..6c32cc9a2 100644 --- a/src/features/run/types.ts +++ b/src/features/run/types.ts @@ -29,6 +29,7 @@ import { goBuildType, goTestType } from "./goTypes"; import { dotnetProjectType, dotnetTestType } from "./dotnetTypes"; import { rakeType, rspecType, rubyScriptType } from "./rubyTypes"; import { djangoTestType } from "./djangoTypes"; +import { fastapiType, flaskType } from "./pythonWebTypes"; import { doctestType, pythonType, unittestType } from "./pythonTypes"; import { phpunitType } from "./phpunitTypes"; import { cypressType } from "./cypressType"; @@ -626,6 +627,8 @@ export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [ rakeType, rspecType, djangoTestType, + flaskType, + fastapiType, phpunitType, dotnetProjectType, dotnetTestType, @@ -706,9 +709,19 @@ export function withParams(config: RunConfig, params: Record, ty : {}), ...(type?.ownsWorkingDirectory ? { cwd: line.cwd ?? null } : {}), ...(line.stop ? { stopCommand: line.stop } : {}), + ...(line.setEnv ? { env: withEnv(config.env, line.setEnv) } : {}), }; } +function withEnv(env: Readonly>, set: Readonly>) { + const out = { ...env }; + for (const [key, value] of Object.entries(set)) { + if (value === null) delete out[key]; + else out[key] = value; + } + return out; +} + /** Whether "Emulate terminal in output console" applies to `config`. */ export function terminalApplies(config: RunConfig, type = typeFor(config.kind)): boolean { return config.kind !== COMPOUND && !config.isTest && type?.terminal !== false && !type?.debugOnly; diff --git a/src/platform/i18n.test.ts b/src/platform/i18n.test.ts index ededaf2f0..5b098d0f5 100644 --- a/src/platform/i18n.test.ts +++ b/src/platform/i18n.test.ts @@ -311,6 +311,9 @@ describe("catalogs", () => { "Java", "Python", "Python {short}", + "FastAPI", + // The FastAPI configuration's Application placeholder. + "main:app", "Flutter {framework}", "Dart {dart}", "C/C++", diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 39bea1892..43b5275ca 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4485,5 +4485,19 @@ "Sign in with GitHub CLI to view and review pull requests.": "Sign in with GitHub CLI to view and review pull requests.", "Find in Documentation": "Find in Documentation", "Previous Match": "Previous Match", - "Next Match": "Next Match" + "Next Match": "Next Match", + "Flask server": "Flask server", + "Run a Flask application with flask run": "Run a Flask application with flask run", + "Set as FLASK_APP: a module or file, optionally with the app or factory (hello:create_app()); empty finds app.py or wsgi.py": "Set as FLASK_APP: a module or file, optionally with the app or factory (hello:create_app()); empty finds app.py or wsgi.py", + "Debug mode": "Debug mode", + "FLASK_DEBUG=1: reload on code changes and show the interactive debugger in the browser": "FLASK_DEBUG=1: reload on code changes and show the interactive debugger in the browser", + "Additional options": "Additional options", + "e.g. --cert adhoc --extra-files config.toml": "e.g. --cert adhoc --extra-files config.toml", + "FastAPI": "FastAPI", + "Run a FastAPI application with uvicorn": "Run a FastAPI application with uvicorn", + "main:app": "main:app", + "The module and the FastAPI instance in it, module:attribute": "The module and the FastAPI instance in it, module:attribute", + "Reload on code changes": "Reload on code changes", + "uvicorn --reload. Debugging stops at breakpoints in the reloaded process while Attach to subprocess automatically while debugging is on (the default); with it off, debugging runs without the reloader": "uvicorn --reload. Debugging stops at breakpoints in the reloaded process while Attach to subprocess automatically while debugging is on (the default); with it off, debugging runs without the reloader", + "e.g. --reload-dir app --log-level debug": "e.g. --reload-dir app --log-level debug" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index f2dabba27..b03a90662 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -11016,5 +11016,19 @@ "Sign in with GitHub CLI to view and review pull requests.": "登录 GitHub CLI 以查看和评审拉取请求。", "Find in Documentation": "在文档中查找", "Previous Match": "上一个匹配项", - "Next Match": "下一个匹配项" + "Next Match": "下一个匹配项", + "Flask server": "Flask 服务器", + "Run a Flask application with flask run": "使用 flask run 运行 Flask 应用", + "Set as FLASK_APP: a module or file, optionally with the app or factory (hello:create_app()); empty finds app.py or wsgi.py": "设为 FLASK_APP:模块或文件,可附带应用或工厂函数(hello:create_app());留空时查找 app.py 或 wsgi.py", + "Debug mode": "调试模式", + "FLASK_DEBUG=1: reload on code changes and show the interactive debugger in the browser": "FLASK_DEBUG=1:代码变更时重新加载,并在浏览器中显示交互式调试器", + "Additional options": "附加选项", + "e.g. --cert adhoc --extra-files config.toml": "例如 --cert adhoc --extra-files config.toml", + "FastAPI": "FastAPI", + "Run a FastAPI application with uvicorn": "使用 uvicorn 运行 FastAPI 应用", + "main:app": "main:app", + "The module and the FastAPI instance in it, module:attribute": "模块及其中的 FastAPI 实例,格式为 module:attribute", + "Reload on code changes": "代码变更时重新加载", + "uvicorn --reload. Debugging stops at breakpoints in the reloaded process while Attach to subprocess automatically while debugging is on (the default); with it off, debugging runs without the reloader": "uvicorn --reload。调试时,只要开启「调试时自动附加到子进程」(默认开启),重新加载后的进程中的断点就会生效;关闭时调试不使用自动重新加载", + "e.g. --reload-dir app --log-level debug": "例如 --reload-dir app --log-level debug" } diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index cfcbb2b14..96ab65430 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -1887,10 +1887,15 @@ export interface RunConfigTypeContribution { /** * What is launched for `params`; null when the type runs no process itself (Compound). * `stop`: a shell command line run on Stop before the process is signalled (`docker stop …`). + * `setEnv`: environment variables the params set (`FLASK_APP`); `null` removes one they set before. */ - commandLine( - params: Readonly>, - ): { command: string; args: string[]; cwd?: string | null; stop?: string | null } | null; + commandLine(params: Readonly>): { + command: string; + args: string[]; + cwd?: string | null; + stop?: string | null; + setEnv?: Readonly>; + } | null; /** Params that reproduce a configuration made elsewhere (detection, older files); null when it doesn't fit. */ paramsFrom?(config: RunConfig): Record | null; /** The type's fields set the working directory (no separate field). */