I am using Visual Studio 2022 on Win11, and trying to get to grips with Python. In particular, I am trying out FastAPI.
I have installed FastAPI and Uvicorn. I have a virtual environment set up for Python 3.9.
How do I get VS to run the Uvicorn server when testing? I am trying to follow the start up guide (https://fastapi.tiangolo.com/tutorial/first-steps/). I have created a main.py file, with the required code. When I try to run it from an interactive console, I type uvicorn -m main:app --reload
.
The console comes back with
File "stdin", line 1
uvicorn -m main:app --reload
^
SyntaxError: invalid syntax
I have tried moving the example code to another file and trying to get uvicorn to run that file, but no joy. I think either uvicorn is not running, or the environment cannot find either uvicorn or the target main.py file.
I have tried running a DOS prompt, executing the python.exe in the venv folder, and trying to point to uvicorn directly...
"C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\python" -m "C:\Users\User\Documents\Visual Studio 2022\Repos\PythonApplicationFastAPITest1\env\Scripts\uvicorn" main:app --reload
...and I get "No module named ...uvicorn".
I got this working with MKrieger1's engagement.
Uvicorn is a self contained app, uvicorn.exe, a server. I was trying to start it in a Python interpreter session, which was failing.
I got it working by running uvicorn in an external DOS prompt. I referenced the uvicorn.exe that had been installed with the FastAPI package. The -m switch did not seem to work.
When in DOS, I changed directory to the project folder holding my main.py file. I then issued the command...
.\env\scripts\uvicorn main:app --reload
...and this started uvicorn.exe, found main.py, app object, and ran it. I was then able to browse to 127.0.0.1:8000 and get my "Hello, world" achievement.
INFO: Will watch for changes in these directories: ['C:\\Users\\User\\Documents\\Visual Studio 2022\\Repos\\PythonApplicationFastAPITest1']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [23000] using WatchFiles
INFO: Started server process [20528]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:49891 - "GET / HTTP/1.1" 200 OK