Code Monkey home page Code Monkey logo

Comments (28)

Christian-Schultz avatar Christian-Schultz commented on April 29, 2024 13

The following works with the pycharm debugger with reload running in a docker-compose remote interpreter

from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
def root():
    a = "a"
    b = "b" + a
    return {"hello world": b}


if __name__ == '__main__':
    uvicorn.run("main:app", host='0.0.0.0', port=8000, reload=True)

Notice the it's "main:app" and not app otherwise you get an error:

WARNING: You must pass the application as an import string to enable 'reload' or 'workers'.

from fastapi.

tiangolo avatar tiangolo commented on April 29, 2024 9

Thanks for your help here @euri10 !

@olegasdo, I hope you found what you needed in the VS Code docs.


Here's one option that might work for you:

You can import uvicorn in your file, instead of calling it directly from the command line, and run it inside (maybe just for development).

from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
def root():
    a = "a"
    b = "b" + a
    return {"hello world": b}


if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=8000)

Then you can use the default VS Code launcher, "Python: Current File (Integrated Terminal)".

It will then stop at your breakpoints, etc.

Here's how it looks:

vscode-launch-debug-vscode

from fastapi.

tiangolo avatar tiangolo commented on April 29, 2024 6

Just in case, there is now a section for Debugging FastAPI applications, with this same information above: https://fastapi.tiangolo.com/tutorial/debugging/

from fastapi.

euri10 avatar euri10 commented on April 29, 2024 5

small concern imho using uvicorn programatically is that you can't use the --debug flag for automatic reload, see https://www.uvicorn.org/deployment/

The reloader is not enabled when running programmatically.

The alternative I use in development mode while in pycharm (not sure about VSCode sorry) is to use a config like this and run the --debug flag, this way auto-reloading works:

Imgur

from fastapi.

robertcoopercode avatar robertcoopercode commented on April 29, 2024 5

The following works with the pycharm debugger with reload running in a docker-compose remote interpreter

from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
def root():
    a = "a"
    b = "b" + a
    return {"hello world": b}


if __name__ == '__main__':
    uvicorn.run("main:app", host='0.0.0.0', port=8000, reload=True)

Notice the it's "main:app" and not app otherwise you get an error:

WARNING: You must pass the application as an import string to enable 'reload' or 'workers'.

This also works with VS Code, I just tried it out.

from fastapi.

yrunts avatar yrunts commented on April 29, 2024 4

Looks like debugging works only if reloader is disabled (I've tried with pdb).

Any ideas on how to overcome this?

from fastapi.

cottrell avatar cottrell commented on April 29, 2024 2

Has anyone figured out the pattern for setting this up for call from IPython REPL and using pdb?

from fastapi.

olegasdo avatar olegasdo commented on April 29, 2024 2

I've noticed that debugging stopped when I've added "--reload" to the arguments list

from fastapi.

bytesemantics avatar bytesemantics commented on April 29, 2024 1

This worked for me...... (assuming your python project is using virtualenv)....

  1. Set up VSCode to use your local virtualenv python exe:
    https://code.visualstudio.com/docs/python/environments

  2. Set up a Debug Configuration in VSCode like:
    { "name": "Python: Uvicorn", "type": "python", "request": "launch", "module": "xxxxxx", "program": "${workspaceRoot}/venv/bin/uvicorn ${module}:app", },

where "xxxxxx" is the module name of your python code containing the FastAPI "app"

  1. I tend to leave all uvicorn runtime configuration to be definable in the app module (rather than exposing in debug launch configuration - but YMMV). e.g.

if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=5000, timeout_keep_alive=60)

from fastapi.

bytesemantics avatar bytesemantics commented on April 29, 2024 1

Hi @softwarebloat - sorry that the above does not work for you. It works for me :-)

This is not a VS Code problem, nor a fastapi problem. The problem is how (and what) you are managing your project python packages with. As stated above - virtualenv approach works fine - as it manages PATH/PYTHONPATH appropriately. VSCode is also designed to support virtualenv environments.

You can either switch to virtualenv - or pursue an integration solution using poetry (with VSCode) - but this certainly is NOT a FastAPI problem or bug. Sorry I can't help further.

from fastapi.

dieros avatar dieros commented on April 29, 2024 1

What I would like to do first, although maybe a bit ambitious, is to PR directly to the source of PyCharm and VS Code, including a runner for Uvicorn. That would allow debugging FastAPI, but also any other ASGI, Starlette directly, Quart, Responder, Bocadillo, etc. So, I think it would be beneficial for everyone. But I have to check their source code to see where those runners live first

@tiangolo sorry for the insistence, did you finally sent PR to PyCharm, related to this "Uvicorn runner" ? If not, I would be interested on helping towards that, if you already have some progress related.
I am actually debugging as explained at https://fastapi.tiangolo.com/tutorial/debugging/ (by the way, thanks, that tutorial was really helpful), but as I added those lines of code

import uvicorn
if __name__ == "__main__":
    uvicorn.run('app.main:app', host="0.0.0.0", port=80, reload=True)

specifically for debugging and are not part of my "original project", it sounds great if we could make Pycharm adding a native Uvicorn runner.

from fastapi.

taffit avatar taffit commented on April 29, 2024 1

Has anyone figured out the pattern for setting this up for call from IPython REPL and using pdb?

Using FastAPI within a docker container and also having problems debugging it from the commandline. A simple import ipdb; ipdb.set_trace() unfortunately doesn't work.

Edit: I had success using web-pdb instead. This opens a console in a web browser to debug. Activation is done similar to ipdb: import web_pdb; web_pdb.set_trace() and then open a tab pointing to http://localhost:5555 (don't forget to expose the port if working with docker container).

from fastapi.

euri10 avatar euri10 commented on April 29, 2024

What examples are you talking about ?
What prevents you from using them ?
If you could be more specific that would help answering.

Docs are very clear and progressive imho, using the parts provided should suffice, if not the tests folder is often a good source of inspiration.

from fastapi.

olegasdo avatar olegasdo commented on April 29, 2024

from fastapi.

euri10 avatar euri10 commented on April 29, 2024

not sure how this is related to FastAPI, this seems more like a general question on how to use vscode.
I'm using pycharm and in order to debug a route you'd simply put a breakpoint in it and call it either with your local browser, or curl, well anything you'd feel comfortable with.
As for vscode seems like debugging is described here: https://code.visualstudio.com/docs/python/debugging that may be a good start.
You could also use the cool pdb.

from fastapi.

olegasdo avatar olegasdo commented on April 29, 2024

Yes, it's more common question. thanks for tips tho.

Regards

from fastapi.

olegasdo avatar olegasdo commented on April 29, 2024

Thank you, Sebastián, that's was exactly what I was looking for.
Also @euri10 thanks for the hints.

from fastapi.

tiangolo avatar tiangolo commented on April 29, 2024

Sorry for the delay, thanks for the hint @euri10 . Actually, I think it would be nice to have a run command for Uvicorn in PyCharm and Uvicorn with everything pre-configured. Or at least docs for how to do it.

Also, in a recent version of Uvicorn, it's now possible to add reload programmatically. But still, I think it would be worth having that directly in the editors. I'll take a note to try and PR that command config to them.

from fastapi.

euri10 avatar euri10 commented on April 29, 2024

@tiangolo I'm not aware of a way to programatically add a configuration command in Pycharm (like the uvicorn one from the screenshot above), it has to be done manually with gui

They are saved in .idea/workspace.xml yet this would be awkward to edit that by hand.

If you ok I can write a PR for Pycharm debug (I'm clueless on other IDE), with a set of screenshots for:

1- fastapi development itself

  • a pytest config (it requires to have PYTHONPATH=docs/src in env vars for instance, which is not obvious at first)

2- any application using fastapi

  • a uvicorn config (like the one above, with the now super mega cool --reload flag)

from fastapi.

wshayes avatar wshayes commented on April 29, 2024

I'm happy to try to create a PR with info on using Docker with fastAPI - just not sure where you'd want it in the docs (e.g. along the lines of: https://medium.com/@williamhayes/fastapi-starlette-debug-vs-prod-5f7561db3a59) or maybe a location for links like that article in the docs.

from fastapi.

tiangolo avatar tiangolo commented on April 29, 2024

Thanks @wshayes ! I think we can have that in the project generators, that are all Docker-based. For example, there's a lot of docs in the generated projects: https://github.com/tiangolo/full-stack-fastapi-postgresql/blob/master/%7B%7Bcookiecutter.project_slug%7D%7D/README.md#backend-local-development-additional-details

@euri10 What I would like to do first, although maybe a bit ambitious, is to PR directly to the source of PyCharm and VS Code, including a runner for Uvicorn. That would allow debugging FastAPI, but also any other ASGI, Starlette directly, Quart, Responder, Bocadillo, etc. So, I think it would be beneficial for everyone. But I have to check their source code to see where those runners live first 😁

from fastapi.

softwarebloat avatar softwarebloat commented on April 29, 2024

Hi guy's,
sorry but none of the above seems to work for me.
when i run the debug, i get an ImportError:
ImportError: attempted relative import with no known parent package

I think i described a little better here

Thanks

from fastapi.

softwarebloat avatar softwarebloat commented on April 29, 2024

Thanks @wshayes ! I think we can have that in the project generators, that are all Docker-based. For example, there's a lot of docs in the generated projects: https://github.com/tiangolo/full-stack-fastapi-postgresql/blob/master/%7B%7Bcookiecutter.project_slug%7D%7D/README.md#backend-local-development-additional-details

@euri10 What I would like to do first, although maybe a bit ambitious, is to PR directly to the source of PyCharm and VS Code, including a runner for Uvicorn. That would allow debugging FastAPI, but also any other ASGI, Starlette directly, Quart, Responder, Bocadillo, etc. So, I think it would be beneficial for everyone. But I have to check their source code to see where those runners live first 😁

@tiangolo did you manage to open a PR to vscode at the end? Thanks 🍻

from fastapi.

cbnfreitas avatar cbnfreitas commented on April 29, 2024

In regards to FastAPI/Uvicorn debugging, considering VSCode on Windows and virtualenv (with PIPENV_VENV_IN_PROJECT=1 to include virtualenv dependencies on the project folder), maybe this hint can be relevant for you. It even includes hot reload :-)

Following @bytesemantics 's answers above, some changes to ..vscode\launch.json were necessay:
{ "version": "0.2.0", "configurations": [ { "name": "Python: Uvicorn", "type": "python", "request": "launch", "program": "${workspaceRoot}\\YOUR-VENV-FOLDER\\Scripts\\uvicorn.exe", "args": [ "YOUR-MODULE-NAME.main:app", "--reload" ], } ] }

Don't forget to change ..vscode\settings.json
{ "python.pythonPath": ".\\YOUR-VENV-FOLDER\\Scripts\\python.exe" }

from fastapi.

Master-Y0da avatar Master-Y0da commented on April 29, 2024

This not working for me...I'm not using docker but I try many ways for start debugging, and gives me this error when I hit f5 at VSCODE :

ModuleNotFoundError: No module named 'fastapi'

This is my code:

 from fastapi import FastAPI
 import uvicorn  

 if __name__ == "__main__":
      uvicorn.run("main:app", host="127.0.0.1", port=8181, reload=True)

from fastapi.

olegasdo avatar olegasdo commented on April 29, 2024

After some pause got back to the FastAPI with a need to debug some.
But Have no luck entering Debug mode on WIndows and VSCode
Tried every suggested way from here and from oficial documentaion and it's just not working. Debug does not stop on the beackpoints even in main.py file, left away aother that are loaded.

Anyone with more suggestions?

from fastapi.

olegasdo avatar olegasdo commented on April 29, 2024

Not sure why, but when showing to a colleague @cbnfreitas suggested solution (well alsmost) started working.
Python path is pointed to the .venv folder in the project dir.
launch.json in VSCode:

{"name":"Python: FastAPI","type":"python","request":"launch","module":"uvicorn",
"env": {
"db_username": "postgres",
"db_password": "",
"host_server": "localhost",
"database_name": "fastapi",
"ssl_mode": "prefer",
"db_server_port": "5432"
},
"args": [
"app.main:app",
"--port",
"5000"
],
"jinja": true
}

Hope this will will someone to save some time searching

from fastapi.

github-actions avatar github-actions commented on April 29, 2024

Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.

from fastapi.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.