FastAPI + Uvicorn = 블레이징 스피드: The Tech Behind the Hype
Grace Collins
Solutions Engineer · Leapcell

What is Uvicorn?
Answer: Uvicorn은 uvloop와 httptools를 기반으로 구축된 매우 빠른 ASGI (Asynchronous Server Gateway Interface) 서버입니다. asyncio를 기반으로 개발된 경량 고효율 웹 서버 프레임워크입니다. Uvicorn은 처음 두 가지 목표를 달성하기 위해 설계되었습니다.
- uvloop와 httptools를 사용하여 매우 빠른 asyncio 서버를 구현합니다.
- ASGI를 기반으로 최소한의 애플리케이션 인터페이스를 구현합니다. 현재 http, websockets, Pub/Sub 브로드캐스트를 지원하며 다른 프로토콜 및 메시지 유형으로 확장할 수 있습니다. 공식 웹사이트: uvicorn (https://uvicorn.org/)
What are uvloop and httptools?
Answer: uvloop는 표준 라이브러리 asyncio에서 이벤트 루프를 대체하는 데 사용됩니다. Cython으로 구현되어 매우 빠르며 asyncio의 속도를 2~4배 향상시킬 수 있습니다. 비동기 코드를 작성하는 데 필수적이므로 asyncio에 익숙하다고 가정합니다. httptools는 Node.js HTTP 파서의 Python 구현입니다.
What is an ASGI server?
Answer: ASGI(Asynchronous Server Gateway Interface)는 네트워크 프로토콜 서비스와 Python 애플리케이션 간의 표준 인터페이스입니다. HTTP, HTTP2 및 WebSocket을 포함한 여러 일반적인 프로토콜 유형을 처리할 수 있습니다. ASGI 프로토콜: https://asgi.readthedocs.io/en/latest/specs/main.html
Briefly introduce Uvicorn
Answer: 현재 Python에는 비동기 게이트웨이 프로토콜 인터페이스가 없습니다. ASGI의 등장은 이러한 격차를 해소합니다. 이제부터는 공통 표준을 사용하여 모든 비동기 프레임워크에 대한 도구를 구현할 수 있습니다. ASGI는 Python이 웹 프레임워크에서 Node.JS 및 Golang과 경쟁하여 고성능 IO 집약적 작업을 달성하는 데 도움이 됩니다. ASGI는 HTTP2와 WebSockets를 지원하지만 WSGI는 지원하지 않습니다. Uvicorn은 현재 HTTP1.1과 WebSocket을 지원하며 HTTP2를 지원할 계획입니다.
Uvicorn Usage
-
Installation Run
pip install uvicorn
-
Create a new
example.py
file
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!', })
-
Start uvicorn from the command line Run
uvicorn example:app
-
Start in script form
import uvicorn async def app(scope, receive, send): ... if __name__ == "__main__": uvicorn.run("example:app", host="127.0.0.1", port=8000, log_level="info")
Uvicorn은 여러 명령어를 지원하며, uvicorn --help
를 통해 확인할 수 있습니다.
➜ ~ uvicorn --help
Usage: uvicorn [OPTIONS] APP
Options:
--host TEXT Bind socket to this host. [default:
127.0.0.1]
--port INTEGER Bind socket to this port. If 0, an available
port will be picked. [default: 8000]
--uds TEXT Bind to a UNIX domain socket.
--fd INTEGER Bind to socket from this file descriptor.
--reload Enable auto-reload.
--reload-dir PATH Set reload directories explicitly, instead
of using the current working directory.
--reload-include TEXT Set glob patterns to include while watching
for files. Includes '*.py' by default; these
defaults can be overridden with `--reload-
exclude`. This option has no effect unless
watchfiles is installed.
--reload-exclude TEXT Set glob patterns to exclude while watching
for files. Includes '.*,.py[cod],.sw.*,
~*' by default; these defaults can be
overridden with `--reload-include`. This
option has no effect unless watchfiles is
installed.
--reload-delay FLOAT Delay between previous and next check if
application needs to be. Defaults to 0.25s.
[default: 0.25]
--workers INTEGER Number of worker processes. Defaults to the
$WEB_CONCURRENCY environment variable if
available, or 1. Not valid with --reload.
--loop [auto|asyncio|uvloop] Event loop implementation. [default: auto]
--http [auto|h11|httptools] HTTP protocol implementation. [default:
auto]
--ws [auto|none|websockets|wsproto]
WebSocket protocol implementation.
[default: auto]
--ws-max-size INTEGER WebSocket max size message in bytes
[default: 16777216]
--ws-max-queue INTEGER The maximum length of the WebSocket message
queue. [default: 32]
--ws-ping-interval FLOAT WebSocket ping interval in seconds.
[default: 20.0]
--ws-ping-timeout FLOAT WebSocket ping timeout in seconds.
[default: 20.0]
--ws-per-message-deflate BOOLEAN
WebSocket per-message-deflate compression
[default: True]
--lifespan [auto|on|off] Lifespan implementation. [default: auto]
--interface [auto|asgi3|asgi2|wsgi]
Select ASGI3, ASGI2, or WSGI as the
application interface. [default: auto]
--env-file PATH Environment configuration file.
--log-config PATH Logging configuration file. Supported
formats:.ini,.json,.yaml.
--log-level [critical|error|warning|info|debug|trace]
Log level. [default: info]
--access-log / --no-access-log Enable/Disable access log.
--use-colors / --no-use-colors Enable/Disable colorized logging.
--proxy-headers / --no-proxy-headers
Enable/Disable X-Forwarded-Proto,
X-Forwarded-For, X-Forwarded-Port to
populate remote address info.
--server-header / --no-server-header
Enable/Disable default Server header.
--date-header / --no-date-header
Enable/Disable default Date header.
--forwarded-allow-ips TEXT Comma separated list of IPs to trust with
proxy headers. Defaults to the
$FORWARDED_ALLOW_IPS environment variable if
available, or '127.0.0.1'.
--root-path TEXT Set the ASGI 'root_path' for applications
submounted below a given URL path.
--limit-concurrency INTEGER Maximum number of concurrent connections or
tasks to allow, before issuing HTTP 503
responses.
--backlog INTEGER Maximum number of connections to hold in
backlog
--limit-max-requests INTEGER Maximum number of requests to service before
terminating the process.
--timeout-keep-alive INTEGER Close Keep-Alive connections if no new data
is received within this timeout. [default:
5]
--timeout-graceful-shutdown INTEGER
Maximum number of seconds to wait for
graceful shutdown.
--ssl-keyfile TEXT SSL key file
--ssl-certfile TEXT SSL certificate file
--ssl-keyfile-password TEXT SSL keyfile password
--ssl-version INTEGER SSL version to use (see stdlib ssl module's)
[default: 17]
--ssl-cert-reqs INTEGER Whether client certificate is required (see
stdlib ssl module's) [default: 0]
--ssl-ca-certs TEXT CA certificates file
--ssl-ciphers TEXT Ciphers to use (see stdlib ssl module's)
[default: TLSv1]
--header TEXT Specify custom default HTTP response headers
as a Name:Value pair
--version Display the uvicorn version and exit.
--app-dir TEXT Look for APP in the specified directory, by
adding this to the PYTHONPATH. Defaults to
the current working directory.
--h11-max-incomplete-event-size INTEGER
For h11, the maximum number of bytes to
buffer of an incomplete event.
--factory Treat APP as an application factory, i.e. a
() -> <ASGI app> callable.
--help Show this message and exit.
➜ ~
Config and Server Instances
To have better control over the configuration and server lifecycle, use uvicorn.Config
and uvicorn.Server
:
import uvicorn async def app(scope, receive, send): ... if __name__ == "__main__": config = uvicorn.Config("main:app", port=5000, log_level="info") server = uvicorn.Server(config) server.run()
If you want to run Uvicorn from an already running asynchronous environment, use uvicorn.Server.serve()
instead:
import asyncio import uvicorn async def app(scope, receive, send): ... async def main(): config = uvicorn.Config("main:app", port=5000, log_level="info") server = uvicorn.Server(config) await server.serve() if __name__ == "__main__": asyncio.run(main())
Starting a FastAPI Project with Uvicorn
import uvicorn from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} if __name__ == '__main__': uvicorn.run(app=app)
Why does FastAPI use Uvicorn?
FastAPI는 현대적인 고성능 웹 프레임워크입니다. Python의 비동기 프로그래밍 기능을 사용하여 웹 애플리케이션의 성능을 향상시킵니다. 반면에 Uvicorn은 uvloop 및 httptools로 구현된 고성능 ASGI 서버로, HTTP 요청을 비동기적으로 처리할 수 있습니다. FastAPI는 Uvicorn이 매우 빠르고 안정적이며 사용하기 쉽기 때문에 Uvicorn을 기본 웹 서버로 사용합니다. 많은 수의 동시 연결을 처리할 때 안정적이고 효율적으로 유지될 수 있습니다. 또한 Uvicorn은 WebSocket 및 HTTP/2와 같은 새로운 기능을 지원하여 FastAPI가 옹호하는 최신 웹 개발 철학과 일치합니다. 따라서 Uvicorn을 FastAPI의 웹 서버로 사용하는 것이 훌륭한 선택입니다.
Leapcell: The Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis
마지막으로 FastAPI 서비스를 배포하는 데 가장 적합한 플랫폼인 Leapcell을 소개하겠습니다.
Leapcell에는 다음과 같은 기능이 있습니다.
-
1. Multi-Language Support JavaScript, Python, Go 또는 Rust로 개발하십시오.
-
2. Deploy unlimited projects for free 사용량에 대해서만 지불하십시오. 요청 없음, 요금 없음.
-
3. Unbeatable Cost Efficiency 유휴 요금 없이 사용한 만큼만 지불하십시오. 예: $25는 평균 응답 시간 60ms에서 6.94M 요청을 지원합니다.
-
4. Streamlined Developer Experience 노력 없는 설정을 위한 직관적인 UI. 완전 자동화된 CI/CD 파이프라인 및 GitOps 통합. 실행 가능한 통찰력을 위한 실시간 메트릭 및 로깅.
-
5. Effortless Scalability and High Performance 쉬운 동시성 처리를 위한 자동 크기 조정. 운영 오버헤드가 없으므로 빌드에만 집중하십시오.
Leapcell Twitter: https://x.com/LeapcellHQ