Ir al contenido
Docs Try Aspire
Docs Try

Python integration

Esta página aún no está disponible en tu idioma.

Python logo

The Aspire Python hosting integration lets you model Python scripts, modules, executables, and ASGI web apps as first-class resources in your AppHost project. Aspire manages virtual environment setup, injects connection strings and service URLs into the Python process, and wires up service discovery and observability automatically.

Aspire CLI — Añadir paquete Aspire.Hosting.Python
aspire add python

La CLI de Aspire es interactiva; asegúrate de seleccionar el resultado adecuado cuando se te pida:

Aspire CLI — Ejemplo de salida
Select an integration to add:
> python (Aspire.Hosting.Python)
> Other results listed as selectable options...

Use AddPythonApp to run a Python script directly:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddPythonApp(
name: "python-api",
projectDirectory: "../python-app",
scriptPath: "main.py")
.WithHttpEndpoint(port: 8000, env: "PORT");
builder.AddProject<Projects.ExampleProject>("example")
.WithReference(python);
builder.Build().Run();

AddPythonApp / addPythonApp requires:

  • name — the resource name shown in the Aspire dashboard
  • projectDirectory / appDirectory — path to the directory containing your Python application
  • scriptPath — the Python script to run, relative to the project directory

Use AddPythonModule to run a Python module (the equivalent of python -m <module>):

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddPythonModule(
name: "python-module",
projectDirectory: "../python-app",
moduleName: "mymodule")
.WithHttpEndpoint(port: 8000, env: "PORT");
builder.Build().Run();

AddPythonModule / addPythonModule requires:

  • name — the resource name shown in the Aspire dashboard
  • projectDirectory / appDirectory — path to the directory containing your Python application
  • moduleName — the Python module to run

Use AddPythonExecutable to run a CLI tool installed in the virtual environment (for example, uvicorn or a custom script):

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddPythonExecutable(
name: "python-tool",
projectDirectory: "../python-app",
executable: "uvicorn",
args: ["main:app", "--host", "0.0.0.0", "--port", "8000"]);
builder.Build().Run();

For ASGI web frameworks like FastAPI, Starlette, and Quart, use AddUvicornApp which pre-configures Uvicorn as the ASGI server:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddUvicornApp(
name: "python-api",
projectDirectory: "../python-app",
appName: "main:app")
.WithHttpEndpoint(port: 8000, env: "PORT");
builder.AddProject<Projects.ExampleProject>("example")
.WithReference(python);
builder.Build().Run();

AddUvicornApp / addUvicornApp requires:

  • name — the resource name shown in the Aspire dashboard
  • projectDirectory / appDirectory — path to the directory containing your Python application
  • appName / app — the ASGI application in module:variable format (for example, main:app for an app variable in main.py)

Configure Uvicorn worker count and log level through environment variables:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddUvicornApp("python-api", "../python-app", "main:app")
.WithHttpEndpoint(port: 8000, env: "PORT")
.WithEnvironment("UVICORN_WORKERS", "4")
.WithEnvironment("UVICORN_LOG_LEVEL", "info");
builder.Build().Run();

Common Uvicorn environment variables:

  • UVICORN_PORT — port to listen on
  • UVICORN_HOST — host to bind to (default: 127.0.0.1)
  • UVICORN_WORKERS — number of worker processes
  • UVICORN_LOG_LEVEL — logging level (debug, info, warning, error)

The Python hosting integration automatically detects and uses a virtual environment in the project directory. By default, if a requirements.txt or pyproject.toml is found, Aspire creates and activates a virtual environment before starting the app.

To specify a custom virtual environment path, use WithVirtualEnvironment:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddPythonApp("python-api", "../python-app", "main.py")
.WithVirtualEnvironment("../python-app/.venv");
builder.Build().Run();

To opt out of automatic virtual environment management, call WithoutVirtualEnvironment in C#:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddPythonApp("python-api", "../python-app", "main.py")
.WithoutVirtualEnvironment();
builder.Build().Run();

Use WithUv to opt into the uv package manager, which installs dependencies significantly faster than pip:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddUvicornApp("python-api", "../python-app", "main:app")
.WithUv()
.WithHttpEndpoint(port: 8000, env: "PORT");
builder.Build().Run();

Use WithPip to explicitly select pip:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddPythonApp("python-api", "../python-app", "main.py")
.WithPip()
.WithHttpEndpoint(port: 8000, env: "PORT");
builder.Build().Run();

Python apps typically read the port from an environment variable. Use WithHttpEndpoint to declare the port and inject the variable name:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddUvicornApp("python-api", "../python-app", "main:app")
.WithHttpEndpoint(port: 8000, env: "PORT");
builder.Build().Run();

A Python app can expose more than one endpoint:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddPythonApp("python-api", "../python-app", "main.py")
.WithHttpEndpoint(port: 8000, env: "HTTP_PORT", name: "http")
.WithHttpEndpoint(port: 8443, env: "HTTPS_PORT", name: "https");
builder.Build().Run();

Declare an HTTP health-check endpoint so Aspire knows when the app is ready:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddUvicornApp("python-api", "../python-app", "main:app")
.WithHttpEndpoint(port: 8000, env: "PORT")
.WithHttpHealthCheck("/health");
builder.Build().Run();

Inject arbitrary environment variables with WithEnvironment:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddPythonApp("python-api", "../python-app", "main.py")
.WithEnvironment("DEBUG", "true")
.WithEnvironment("LOG_LEVEL", "debug");
builder.Build().Run();

Reference other Aspire resources from a Python app using WithReference. Aspire injects the connection string as the ConnectionStrings__<resourcename> environment variable in the Python process:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var db = builder.AddPostgres("postgres")
.AddDatabase("mydb");
var python = builder.AddPythonApp("python-api", "../python-app", "main.py")
.WithReference(db);
builder.Build().Run();

Read the connection string in Python using the ConnectionStrings__mydb environment variable (double-underscore separator for Python/shell environments):

Python — main.py
import os
connection_string = os.environ.get("ConnectionStrings__mydb")

By default, Python apps run over HTTP in local development. To enable HTTPS, use WithHttpsEndpoint together with WithHttpsDeveloperCertificate:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var python = builder.AddUvicornApp("python-api", "../python-app", "main:app")
.WithHttpsEndpoint(port: 8443, env: "PORT")
.WithHttpsDeveloperCertificate();
builder.Build().Run();

WithHttpsDeveloperCertificate exports the ASP.NET Core development certificate and injects it into the Python process as environment variables. Read those variables in your Uvicorn startup:

Python — main.py
import os
import uvicorn
if __name__ == "__main__":
ssl_keyfile = os.environ.get("ASPNETCORE_Kestrel__Certificates__Default__KeyPath")
ssl_certfile = os.environ.get("ASPNETCORE_Kestrel__Certificates__Default__Path")
uvicorn.run(
"main:app",
host="0.0.0.0",
port=int(os.environ.get("PORT", 8443)),
ssl_keyfile=ssl_keyfile,
ssl_certfile=ssl_certfile,
)

By default, Aspire services are only accessible within the distributed application. Use WithExternalHttpEndpoints to expose a service to external traffic:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var internalApi = builder.AddUvicornApp("internal-api", "../internal-api", "main:app")
.WithHttpEndpoint(port: 8001, env: "PORT");
// internalApi is NOT exposed publicly — only reachable by other Aspire resources
var publicApi = builder.AddUvicornApp("public-api", "../public-api", "main:app")
.WithHttpEndpoint(port: 8000, env: "PORT")
.WithExternalHttpEndpoints();
// publicApi IS exposed publicly
builder.AddProject<Projects.WebFrontend>("frontend")
.WithReference(internalApi)
.WithReference(publicApi);
builder.Build().Run();

The Python hosting integration provides full debugging support in Visual Studio Code:

  1. Install the Aspire VS Code extension
  2. Set breakpoints in your Python code
  3. Run the Aspire app host
  4. The debugger automatically attaches to your Python application

When deploying your Aspire application, the Python hosting integration automatically generates production-ready Dockerfiles for your Python services:

# Auto-generated Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "main.py"]