FastAPI as a Windows service

2024/10/1 23:48:29

I am trying to run FastAPI as a windows service.Couldn't find any documentation or any article to run Uvicorn as a Window's service. I tried using NSSM as well but my windows service stops.

Answer

I managed to run FastAPI with uvicorn as a Windows Service using NSSM.

I had to deploy uvicorn programatically, basically run uvicorn directly from your Python script, then create and install a custom service with NSSM.

Here's a small example based on FastAPI's example, but instead of running it with uvicorn main:app --reload from the command line, you add uvicorn.run(app, **config) with your own config.

from fastapi import FastAPI
import uvicornapp = FastAPI()@app.get("/")
def read_root():return {"Hello": "World"}if __name__ == "__main__":uvicorn.run("main:app", host="127.0.0.1", port=5000, log_level="info")

Then you can install it with NSSM using the standard nssm install command

nssm.exe install "FastAPIWindowsService" "C:\Scripts\FastAPIWindowsService\venv\Scripts\python.exe" "C:\Scripts\FastAPIWindowsService\src\main.py"

Change your service name, the path of your python.exe, and the path of your script accordingly. Your service should appear in the Windows Services Manager when installed.

Hope this helps, and works for you!

Edit: My experience with installing the service with NSSM, as in the example above, is that it would not correctly utilise my virtual environment.

My preferred method now is to use a bat-file that first activates the virtual environment, then runs the desired script. The bat-file can be named whatever you prefer, for example run_app.bat, placed in the same folder as your script, with the following contents:

call venv\Scripts\activate.bat
call python src\main.py

I then use the standard nssm install command, but only provide the service name, as I use NSSM’s user interface to fill in the rest of my required information – file path for example, as shown here:

NSSM service installer user interface

Again, hope this helps and works for you!

https://en.xdnf.cn/q/70915.html

Related Q&A

Why not use runserver for production at Django?

Everywhere i see that uWSGI and Gunicorn are recommended for production mode from everyone. However, there is a lot more suffering to operate with it, the python manage.py runserver is more faster, sim…

How to create decorator for lazy initialization of a property

I want to create a decorator that works like a property, only it calls the decorated function only once, and on subsequent calls always return the result of the first call. An example:def SomeClass(obj…

How to convert a 24-bit wav file to 16 or 32 bit files in python3

I am trying to make spectrograms of a bunch of .wav files so I can further analyze them(in python 3.6), however, I keep getting this nasty errorValueError: Unsupported bit depth: the wav file has 24-bi…

Get consistent Key error: \n [duplicate]

This question already has answers here:How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?(23 answers)Closed 8 years ago.When trying to run a script containin…

Cannot take the length of Shape with unknown rank

I have a neural network, from a tf.data data generator and a tf.keras model, as follows (a simplified version-because it would be too long):dataset = ...A tf.data.Dataset object that with the next_x me…

Pre-fill new functions in Eclipse and Pydev with docstring and Not Implemented exception

I am editing my Python source code with Eclipse and Pydev.I want to document all of my functions and raise a "Not Implemented" exception whenever a function have not yet been implemented. For…

How to serialize hierarchical relationship in Django REST

I have a Django model that is hierarchical using django-mptt, which looks like:class UOMCategory(MPTTModel, BaseModel):"""This represents categories of different unit of measurements.&qu…

Django: Loading another template on click of a button

Ive been working on a django project for a few weeks now, just playing around so that I can get the hang of it. I am a little bit confused. I have a template now called "home.html". I was wo…

Given two python lists of same length. How to return the best matches of similar values?

Given are two python lists with strings in them (names of persons):list_1 = [J. Payne, George Bush, Billy Idol, M Stuart, Luc van den Bergen] list_2 = [John Payne, George W. Bush, Billy Idol, M. Stuart…

Extracting Javascript gettext messages using Babel CLI extractor

It is stated here that Babel can extract gettext messages for Python and Javascript files.Babel comes with a few builtin extractors: python (which extractsmessages from Python source files), javascript…