Search code examples
pythongunicornuvicorn

gunicorn (uvicorn). run programatically or via command line?


Is there any difference if I run uvicorn (gunicorn) programatically or via command line in production environment?

command line:

uvicorn --host ${HOST} --port ${PORT} --workers ${NUM_OF_WORKERS} --log-config ${FILE_PATH}

programatically

uvicorn.run(
  'main:app', host=host, port=port, reload=False,
  workers=workers_num, log_config=log_config
)
python main.py

Solution

  • I will try to answer by myself according to hint from @Klaus D.

    uvicorn executable file is:

    #!/usr/local/bin/python3.8
    # -*- coding: utf-8 -*-
    import re
    import sys
    from uvicorn.main import main
    if __name__ == '__main__':
        sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
        sys.exit(main())
    

    Where main() is:

    def main(
      ...
      many_arguments_here
      ...
    ) -> None:
      sys.path.insert(0, app_dir)
      run(app, **kwargs)
    

    So, if we run uvicorn programatically like

    if __name__ == '__main__':
      import sys
    
      # app_dir default value if nothing set
      app_dir = "."
      sys.path.insert(0, app_dir)
      sys.exit(
        uvicorn.run(
          'main:app', host=host, port=port, reload=False,
          workers=workers_num, log_config=log_config
        )
      )
    

    That will be same as run uvicorn via command line