FastAPI + Uvicorn = Rasante Geschwindigkeit: Die Technologie hinter dem Hype
Grace Collins
Solutions Engineer · Leapcell

Was ist Uvicorn?
Antwort: Uvicorn ist ein sehr schneller ASGI-Server (Asynchronous Server Gateway Interface), der auf uvloop und httptools basiert. Es ist ein leichtgewichtiges und effizientes Webserver-Framework, das auf Basis von asyncio entwickelt wurde. Uvicorn wurde ursprünglich entwickelt, um zwei Ziele zu erreichen:
- Einen extrem schnellen asyncio-Server mit uvloop und httptools zu implementieren.
- Eine minimale Anwendungsschnittstelle basierend auf ASGI zu implementieren. Es unterstützt derzeit http, Websockets, Pub/Sub-Broadcasts und kann auf andere Protokolle und Nachrichtentypen erweitert werden. Offizielle Website: uvicorn (https://uvicorn.org/)
Was sind uvloop und httptools?
Antwort: uvloop wird verwendet, um die Event Loop in der Standardbibliothek asyncio zu ersetzen. Es ist mit Cython implementiert und sehr schnell, wodurch die Geschwindigkeit von asyncio um das 2- bis 4-fache erhöht werden kann. Ich gehe davon aus, dass Sie mit asyncio vertraut sind, da es für das Schreiben von asynchronem Code unerlässlich ist. httptools ist eine Python-Implementierung des Node.js HTTP-Parsers.
Was ist ein ASGI-Server?
Antwort: ASGI, das Asynchronous Server Gateway Interface, ist eine Standardschnittstelle zwischen Netzwerkprotokolldiensten und Python-Anwendungen. Es kann mehrere gängige Protokolltypen verarbeiten, darunter HTTP, HTTP2 und WebSocket. ASGI-Protokoll: https://asgi.readthedocs.io/en/latest/specs/main.html
Kurze Einführung in Uvicorn
Antwort: Derzeit fehlt Python eine asynchrone Gateway-Protokollschnittstelle. Das Aufkommen von ASGI schließt diese Lücke. Von nun an können wir einen gemeinsamen Standard verwenden, um Tools für alle asynchronen Frameworks zu implementieren. ASGI hilft Python, mit Node.JS und Golang in Webframeworks zu konkurrieren, mit dem Ziel, hochperformante IO-intensive Aufgaben zu erreichen. ASGI unterstützt HTTP2 und WebSockets, während WSGI dies nicht tut. Uvicorn unterstützt derzeit HTTP1.1 und WebSocket und plant, HTTP2 zu unterstützen.
Uvicorn-Verwendung
-
Installation Führen Sie
pip install uvicorn
aus -
Erstellen Sie eine neue
example.py
-Datei
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!', })
-
Starten Sie Uvicorn über die Befehlszeile Führen Sie
uvicorn example:app
aus -
Starten im Skriptformat
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 unterstützt mehrere Befehle, die mit uvicorn --help
angezeigt werden können.
➜ ~ 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.
➜ ~
Konfigurations- und Serverinstanzen
Um eine bessere Kontrolle über die Konfiguration und den Serverlebenszyklus zu haben, verwenden Sie uvicorn.Config
und 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()
Wenn Sie Uvicorn aus einer bereits laufenden asynchronen Umgebung ausführen möchten, verwenden Sie stattdessen uvicorn.Server.serve()
:
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())
Starten eines FastAPI-Projekts mit 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)
Warum verwendet FastAPI Uvicorn?
FastAPI ist ein modernes, hochleistungsfähiges Webframework. Es nutzt die asynchronen Programmierfunktionen von Python, um die Leistung von Webanwendungen zu verbessern. Uvicorn hingegen ist ein hochleistungsfähiger ASGI-Server, der mit uvloop und httptools implementiert wurde und HTTP-Anfragen asynchron verarbeiten kann. FastAPI verwendet Uvicorn als seinen Standard-Webserver, da Uvicorn sehr schnell, zuverlässig und einfach zu bedienen ist. Es kann stabil und effizient bleiben, wenn eine große Anzahl von gleichzeitigen Verbindungen verarbeitet wird. Darüber hinaus unterstützt Uvicorn neue Funktionen wie WebSocket und HTTP/2, die mit der modernen Webentwicklungsphilosophie übereinstimmen, die von FastAPI befürwortet wird. Daher ist die Verwendung von Uvicorn als Webserver für FastAPI eine ausgezeichnete Wahl.
Leapcell: Die Serverlose Plattform der nächsten Generation für Webhosting, Asynchrone Aufgaben und Redis
Abschließend möchte ich die Plattform vorstellen, die sich am besten für die Bereitstellung von FastAPI-Diensten eignet: Leapcell.
Leapcell bietet die folgenden Funktionen:
-
1. Unterstützung mehrerer Sprachen Entwickeln Sie mit JavaScript, Python, Go oder Rust.
-
2. Stellen Sie unbegrenzt Projekte kostenlos bereit Zahlen Sie nur für die Nutzung - keine Anfragen, keine Gebühren.
-
3. Unschlagbare Kosteneffizienz Pay-as-you-go ohne Leerlaufgebühren. Beispiel: 25 US-Dollar unterstützen 6,94 Millionen Anfragen bei einer durchschnittlichen Antwortzeit von 60 ms.
-
4. Optimierte Entwicklererfahrung Intuitive Benutzeroberfläche für mühelose Einrichtung. Vollautomatische CI/CD-Pipelines und GitOps-Integration. Echtzeitmetriken und -protokollierung für umsetzbare Erkenntnisse.
-
5. Mühelose Skalierbarkeit und hohe Leistung Automatische Skalierung zur einfachen Bewältigung hoher Parallelität. Null Betriebsaufwand - konzentrieren Sie sich einfach auf das Erstellen.
Entdecken Sie mehr in der Dokumentation!
Leapcell Twitter: https://x.com/LeapcellHQ