Home > OS >  Need assistance on routing requests while debugging python-FastAPI under VSCode
Need assistance on routing requests while debugging python-FastAPI under VSCode

Time:04-14

This is my first effort to use VSCode for python development and I'm running into problems I have no idea why.

The immediate problem is I can't seem to get uvicorn to route my browser request to my fastAPI module. Here's the relevant parts of my code:

import uvicorn
from fastapi import FastAPI, Header, HTTPException, Request, status, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel

# initialize (FAST) API framework.
app = FastAPI()

# configure Cross-Origin Resource Sharing configuration
# TODO : Have to enter all the allowed origins
origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)   

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)
    
################################
#   endpoint definitions       #
################################ 

# test endpoint
@app.get("/")
async def test():
    x=0
    return x

So I set my breakpoint on the "x = 0" statment and run the debugger and all is well no exceptions and uvicorn seems to be waiting for a request.

My browser request is http://127.0.0.1:8000/

What I see in the terminal window is this:

INFO:     Started server process [22764]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL C to quit)
INFO:     127.0.0.1:64541 - "GET /incentives HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:64544 - "GET / HTTP/1.1" 404 Not Found

I've poured through the documentation I can find and tried a few permutations but to no success. I never hit the break-point.

I've also tried setting up a "launch.json" file under the VSCode folder but then doesn't seem to do anything, and does not seem to start the uvicron task or set my environment variables.

CodePudding user response:

You have an ordering problem. Your function never gets defined, because uvicorn.run never returns. Define the functions FIRST.

  • Related