[Python] FastAPI server crashes silently on startup with async libraries

Discussão em 'Python' iniciado por Stack, Junho 21, 2025.

  1. Stack

    Stack Membro Participativo

    (ERR_CONNECTION_REFUSED) Body: I'm developing a backend for a project using FastAPI and Uvicorn on a Windows machine. When I try to launch the server, it starts up, prints the initial "Uvicorn running on..." message, and then immediately crashes without any traceback or error message. The log file I configured remains empty. When I try to access the URL in my browser, I get ERR_CONNECTION_REFUSED. I suspect the issue might be related to my environment or a subtle bug in my async code, but I've run out of ideas on how to debug it.

    The Environment:


    OS: Windows 10

    Python: Using a venv virtual environment.

    Problematic Detail: I also have a global conda installation. When I activate my virtual environment, my prompt sometimes shows (venv) (base), which suggests a potential conflict. What Happens: I run the server using a batch script (run_backend.bat) designed to isolate the environment:

    :: run_backend.bat
    @echo off
    set VENV_DIR=%CD%\venv
    set PYTHON_EXE=%VENV_DIR%\Scripts\python.exe
    set PYTHON_PATH=%CD%
    set PYTHONNOUSERSITE=1
    set PYTHONHOME=%VENV_DIR%
    echo Starting backend server using isolated Python environment...
    "%PYTHON_EXE%" -m uvicorn main:app --reload --host 0.0.0.0 --port 8000


    —The terminal shows this output, and then immediately exits:

    Starting backend server using isolated Python environment...
    INFO: Will watch for changes in these directories: ['.']
    INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
    INFO: Started reloader process [12345] using WatchFiles

    What I've Debugged So Far:


    Sync-in-Async Bug: My biggest lead was finding that my custom Supabase client was using synchronous libraries (httpx.Client and postgrest.PostgrestClient) inside an async FastAPI app. This seemed like a classic deadlock scenario. I have since refactored the entire client to be fully asynchronous. The server still crashes silently even after this fix. Environment Isolation: I've tried running from a fresh terminal where (base) doesn't show up, and I've used the batch script above which sets PYTHONHOME to force the use of the venv. The result is the same. Import Chain: The crash happens before any endpoint is hit, so it must be on startup. I have try...except blocks in my main.py around the router imports, but they don't catch anything.

    Relevant Code:


    Here are the key parts of my application. main.py (Simplified):

    from fastapi import FastAPI
    import uvicorn
    import logging
    import traceback
    # --- Logging Setup ---
    # (This file is created but remains empty)
    logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[logging.FileHandler('app.log')]
    )
    logger = logging.getLogger(__name__)
    app = FastAPI()
    # --- Import Routers ---
    try:
    # I have multiple routers like this
    from api.routes import auth, conversations
    app.include_router(auth.router)
    app.include_router(conversations.router)
    except Exception as e:
    # This block is never reached
    logger.error(f"Error including router: {str(e)}")
    traceback.print_exc()
    @app.get("/")
    async def root():
    return {"message": "API is running"}
    if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)


    api/services/supabase_client.py (The refactored ASYNC version): This is my custom client that interacts with Supabase.

    import os
    import logging
    import httpx
    from typing import Dict, Any, Optional
    from postgrest import AsyncPostgrestClient # <-- Changed to Async
    from pathlib import Path
    from dotenv import load_dotenv
    logger = logging.getLogger(__name__)
    class SupabaseClient:
    def __init__(self, supabase_url: Optional[str] = None, supabase_key: Optional[str] = None):
    # ... (load env vars) ...
    self.supabase_url = supabase_url or os.getenv("SUPABASE_URL")
    self.supabase_key = supabase_key or os.getenv("SUPABASE_SERVICE_KEY")
    # Switched to AsyncClient
    self.http_client = httpx.AsyncClient(base_url=self.supabase_url, headers={...})

    rest_url = f"{self.supabase_url}/rest/v1"
    # Switched to AsyncPostgrestClient
    self.postgrest_client = AsyncPostgrestClient(rest_url, headers={...})
    def table(self, table_name: str):
    return TableReference(self.postgrest_client, table_name)
    class TableReference:
    def __init__(self, postgrest_client: AsyncPostgrestClient, table_name: str):
    self.client = postgrest_client
    self.table_name = table_name
    # ... (methods like select, eq, etc. that build the query) ...
    # The final call is now async
    async def execute(self):
    # ... (builds the final query from parts) ...
    query = self.client.from_(self.table_name).select(...) # etc.
    try:
    response = await query.execute() # <-- Now awaited
    return ExecutionResult(response)
    except Exception as e:
    logger.error(f"Error executing query: {str(e)}")
    return ExecutionResult({"data": []})
    class ExecutionResult:
    def __init__(self, response):
    self.data = response.data if hasattr(response, "data") else []
    self.count = len(self.data)
    def create_client():
    return SupabaseClient()

    My Question:


    Given that I've already fixed the sync-vs-async bug, what could still be causing my FastAPI server to crash silently on startup? How can I get any kind of error message to appear?

    Continue reading...

Compartilhe esta Página