Top Related Projects
FastAPI framework, high performance, easy to learn, fast to code, ready for production
The Python micro framework for building web applications.
The Web framework for perfectionists with deadlines.
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
Asynchronous HTTP client/server framework for asyncio and Python
Source for the TechEmpower Framework Benchmarks project
Quick Overview
Uvicorn is a lightning-fast ASGI server implementation, using uvloop and httptools for optimal performance. It's designed to be the go-to server for running Python web applications, particularly those built with ASGI frameworks like FastAPI or Starlette.
Pros
- Extremely fast performance due to its use of uvloop and httptools
- Easy to use and configure
- Supports both HTTP/1.1 and WebSocket protocols
- Integrates well with popular ASGI frameworks
Cons
- Limited to ASGI applications only
- Requires additional dependencies for optimal performance (uvloop, httptools)
- May have a steeper learning curve for beginners compared to simpler WSGI servers
- Not as feature-rich as some more comprehensive server solutions
Code Examples
- Basic usage with an ASGI app:
import uvicorn
async def app(scope, receive, send):
assert scope['type'] == 'http'
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})
await send({
'type': 'http.response.body',
'body': b'Hello, World!',
})
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
- Using Uvicorn with FastAPI:
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
- Configuring Uvicorn with additional options:
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"myapp:app",
host="0.0.0.0",
port=8000,
reload=True,
ssl_keyfile="key.pem",
ssl_certfile="cert.pem",
workers=4
)
Getting Started
To get started with Uvicorn, follow these steps:
-
Install Uvicorn:
pip install uvicorn[standard]
-
Create a simple ASGI application (e.g.,
app.py
):async def app(scope, receive, send): await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ], }) await send({ 'type': 'http.response.body', 'body': b'Hello, World!', })
-
Run the application with Uvicorn:
uvicorn app:app
Your application will now be running on http://127.0.0.1:8000
.
Competitor Comparisons
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Pros of FastAPI
- High-performance web framework with automatic API documentation
- Built-in data validation and serialization using Pydantic models
- Supports asynchronous programming with modern Python features
Cons of FastAPI
- Steeper learning curve for beginners compared to simpler frameworks
- Requires additional dependencies for full functionality
- May be overkill for small, simple projects
Code Comparison
FastAPI:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Uvicorn:
async def app(scope, receive, send):
assert scope['type'] == 'http'
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})
await send({
'type': 'http.response.body',
'body': b'Hello, world!',
})
Key Differences
- FastAPI is a full-featured web framework, while Uvicorn is an ASGI server
- FastAPI provides higher-level abstractions and tools for API development
- Uvicorn focuses on serving ASGI applications efficiently
- FastAPI can use Uvicorn as its underlying server
Use Cases
- Choose FastAPI for building complex APIs with automatic documentation
- Use Uvicorn for serving ASGI applications or as a server for other frameworks
- Combine both by using Uvicorn to serve FastAPI applications in production
The Python micro framework for building web applications.
Pros of Flask
- Mature and well-established web framework with a large ecosystem
- Simple and intuitive API for building web applications
- Extensive documentation and community support
Cons of Flask
- Synchronous by default, which can limit performance for high-concurrency applications
- Requires additional libraries for more advanced features (e.g., ORM, form validation)
- Less suitable for building large, complex applications compared to more opinionated frameworks
Code Comparison
Flask:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
Uvicorn (with FastAPI):
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
async def hello():
return {'message': 'Hello, World!'}
Key Differences
- Flask is a full-featured web framework, while Uvicorn is an ASGI server that can be used with various ASGI frameworks
- Uvicorn is designed for high-performance, asynchronous applications, whereas Flask is primarily synchronous
- Flask provides a more batteries-included approach, while Uvicorn focuses on serving ASGI applications efficiently
Use Cases
- Flask: Ideal for small to medium-sized web applications, prototyping, and projects that don't require high concurrency
- Uvicorn: Best suited for high-performance, asynchronous applications, often used in conjunction with ASGI frameworks like FastAPI or Starlette
The Web framework for perfectionists with deadlines.
Pros of Django
- Full-featured web framework with built-in ORM, admin interface, and authentication system
- Large ecosystem with extensive third-party packages and community support
- Follows the "batteries included" philosophy, providing a complete solution out of the box
Cons of Django
- Heavier and more complex, which can lead to slower performance for simple applications
- Steeper learning curve for beginners due to its comprehensive nature
- Less flexibility in choosing components, as it's more opinionated about its structure
Code Comparison
Django (URL routing):
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.hello_world, name='hello_world'),
]
Uvicorn (with FastAPI for comparison):
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
async def hello_world():
return {"message": "Hello, World!"}
While Django provides a more structured approach to URL routing, Uvicorn (typically used with frameworks like FastAPI) offers a more lightweight and straightforward method for defining routes. Django's approach is part of its comprehensive framework, while Uvicorn's simplicity aligns with its focus on being a fast ASGI server.
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
Pros of Tornado
- More mature and battle-tested, with a longer history of production use
- Supports both synchronous and asynchronous programming models
- Includes a full-featured web framework with routing, templating, and authentication
Cons of Tornado
- Generally slower performance compared to modern ASGI servers
- Less active development and community support in recent years
- Steeper learning curve for developers new to asynchronous programming
Code Comparison
Tornado:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, World!")
app = tornado.web.Application([(r"/", MainHandler)])
app.listen(8000)
tornado.ioloop.IOLoop.current().start()
Uvicorn (with FastAPI):
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
# Run with: uvicorn main:app
Uvicorn focuses on being a lightweight ASGI server, while Tornado provides a more comprehensive web framework. Uvicorn is typically used with other ASGI frameworks like FastAPI or Starlette, offering better performance and modern async support. Tornado, however, offers a complete solution out of the box, including both server and framework components.
Asynchronous HTTP client/server framework for asyncio and Python
Pros of aiohttp
- More comprehensive framework with both client and server capabilities
- Supports WebSockets natively
- Extensive middleware and plugin ecosystem
Cons of aiohttp
- Steeper learning curve due to more complex API
- Slower performance compared to Uvicorn for simple HTTP requests
- Less focus on ASGI compatibility
Code Comparison
aiohttp server example:
from aiohttp import web
async def handle(request):
return web.Response(text="Hello, World!")
app = web.Application()
app.add_routes([web.get('/', handle)])
web.run_app(app)
Uvicorn server example:
async def app(scope, receive, send):
assert scope['type'] == 'http'
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})
await send({
'type': 'http.response.body',
'body': b'Hello, World!',
})
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
Source for the TechEmpower Framework Benchmarks project
Pros of FrameworkBenchmarks
- Comprehensive benchmarking suite for web frameworks across multiple languages
- Provides standardized performance metrics for comparing different frameworks
- Regularly updated with new frameworks and test scenarios
Cons of FrameworkBenchmarks
- More complex setup and configuration compared to Uvicorn
- Requires more resources to run full benchmark suite
- May not reflect real-world performance for specific use cases
Code Comparison
FrameworkBenchmarks (Python FastAPI example):
@app.get("/json")
def json_serialization():
return {"message": "Hello, World!"}
@app.get("/plaintext")
def plaintext():
return PlainTextResponse(b"Hello, World!")
Uvicorn (ASGI example):
async def app(scope, receive, send):
assert scope['type'] == 'http'
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})
await send({
'type': 'http.response.body',
'body': b'Hello, world!',
})
FrameworkBenchmarks focuses on standardized benchmarking across frameworks, while Uvicorn is a lightweight ASGI server. The code examples show how FrameworkBenchmarks uses specific web frameworks (e.g., FastAPI) for testing, whereas Uvicorn provides a low-level ASGI interface for handling requests.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
An ASGI web server, for Python.
Documentation: https://www.uvicorn.org
Uvicorn is an ASGI web server implementation for Python.
Until recently Python has lacked a minimal low-level server/application interface for async frameworks. The ASGI specification fills this gap, and means we're now able to start building a common set of tooling usable across all async frameworks.
Uvicorn supports HTTP/1.1 and WebSockets.
Quickstart
Install using pip
:
$ pip install uvicorn
This will install uvicorn with minimal (pure Python) dependencies.
$ pip install 'uvicorn[standard]'
This will install uvicorn with "Cython-based" dependencies (where possible) and other "optional extras".
In this context, "Cython-based" means the following:
- the event loop
uvloop
will be installed and used if possible. - the http protocol will be handled by
httptools
if possible.
Moreover, "optional extras" means that:
- the websocket protocol will be handled by
websockets
(should you want to usewsproto
you'd need to install it manually) if possible. - the
--reload
flag in development mode will usewatchfiles
. - windows users will have
colorama
installed for the colored logs. python-dotenv
will be installed should you want to use the--env-file
option.PyYAML
will be installed to allow you to provide a.yaml
file to--log-config
, if desired.
Create an application, in example.py
:
async def app(scope, receive, send):
assert scope['type'] == 'http'
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
(b'content-type', b'text/plain'),
],
})
await send({
'type': 'http.response.body',
'body': b'Hello, world!',
})
Run the server:
$ uvicorn example:app
Why ASGI?
Most well established Python Web frameworks started out as WSGI-based frameworks.
WSGI applications are a single, synchronous callable that takes a request and returns a response. This doesnât allow for long-lived connections, like you get with long-poll HTTP or WebSocket connections, which WSGI doesn't support well.
Having an async concurrency model also allows for options such as lightweight background tasks, and can be less of a limiting factor for endpoints that have long periods being blocked on network I/O such as dealing with slow HTTP requests.
Alternative ASGI servers
A strength of the ASGI protocol is that it decouples the server implementation from the application framework. This allows for an ecosystem of interoperating webservers and application frameworks.
Daphne
The first ASGI server implementation, originally developed to power Django Channels, is the Daphne webserver.
It is run widely in production, and supports HTTP/1.1, HTTP/2, and WebSockets.
Any of the example applications given here can equally well be run using daphne
instead.
$ pip install daphne
$ daphne app:App
Hypercorn
Hypercorn was initially part of the Quart web framework, before being separated out into a standalone ASGI server.
Hypercorn supports HTTP/1.1, HTTP/2, and WebSockets.
It also supports the excellent trio
async framework, as an alternative to asyncio
.
$ pip install hypercorn
$ hypercorn app:App
Mangum
Mangum is an adapter for using ASGI applications with AWS Lambda & API Gateway.
Granian
Granian is an ASGI compatible Rust HTTP server which supports HTTP/2, TLS and WebSockets.
Uvicorn is BSD licensed code.
Designed & crafted with care.
— 𦠗
Top Related Projects
FastAPI framework, high performance, easy to learn, fast to code, ready for production
The Python micro framework for building web applications.
The Web framework for perfectionists with deadlines.
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
Asynchronous HTTP client/server framework for asyncio and Python
Source for the TechEmpower Framework Benchmarks project
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot