Python / Uvicorn Fundamentals Interview Questions
How do you run Uvicorn programmatically using uvicorn.run() and uvicorn.Config/Server?
Beyond the CLI, Uvicorn can be configured and launched entirely from Python code. This is useful when you need to customise server startup, integrate it into a larger application, or run it from within an existing async event loop.
import uvicorn # Method 1: uvicorn.run() - simplest programmatic start if __name__ == "__main__": uvicorn.run( "main:app", # string import path host="0.0.0.0", port=8000, reload=True, # development only log_level="info", ) # You can also pass the app object directly (no reload support): # uvicorn.run(app, host="0.0.0.0", port=8000) # Method 2: uvicorn.Config + uvicorn.Server - more control import uvicorn if __name__ == "__main__": config = uvicorn.Config("main:app", port=5000, log_level="info") server = uvicorn.Server(config) server.run() # Method 3: Running inside an existing async loop import asyncio import uvicorn async def main(): config = uvicorn.Config("main:app", port=5000, log_level="info") server = uvicorn.Server(config) await server.serve() # use serve() not run() inside async context if __name__ == "__main__": asyncio.run(main())
Important distinction: when passing the app object directly (not a string) to uvicorn.run(), the reload option is not available because the reloader must re-import the module by name. Always use the 'module:attribute' string form when reload=True.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
