1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
|
From Flask
----------
ASGI vs WSGI
~~~~~~~~~~~~
`Flask <https://flask.palletsprojects.com>`_ is a WSGI framework, whereas Litestar
is built using the modern `ASGI <https://asgi.readthedocs.io>`_ standard. A key difference
is that *ASGI* is built with async in mind.
While Flask has added support for ``async/await``, it remains synchronous at its core;
The async support in Flask is limited to individual endpoints.
What this means is that while you can use ``async def`` to define endpoints in Flask,
**they will not run concurrently** - requests will still be processed one at a time.
Flask handles asynchronous endpoints by creating an event loop for each request, run the
endpoint function in it, and then return its result.
ASGI on the other hand does the exact opposite; It runs everything in a central event loop.
Litestar then adds support for synchronous functions by running them in a non-blocking way
*on the event loop*. What this means is that synchronous and asynchronous code both run
concurrently.
Routing
~~~~~~~
.. tab-set::
.. tab-item:: Flask
:sync: flask
.. code-block:: python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Index Page"
@app.route("/hello")
def hello():
return "Hello, World"
.. tab-item:: Litestar
:sync: litestar
.. code-block:: python
from litestar import Litestar, get
@get("/")
def index() -> str:
return "Index Page"
@get("/hello")
def hello() -> str:
return "Hello, World"
app = Litestar([index, hello])
Path parameters
^^^^^^^^^^^^^^^
.. tab-set::
.. tab-item:: Flask
:sync: flask
.. code-block:: python
from flask import Flask
app = Flask(__name__)
@app.route("/user/<username>")
def show_user_profile(username):
return f"User {username}"
@app.route("/post/<int:post_id>")
def show_post(post_id):
return f"Post {post_id}"
@app.route("/path/<path:subpath>")
def show_subpath(subpath):
return f"Subpath {subpath}"
.. tab-item:: Litestar
:sync: litestar
.. code-block:: python
from litestar import Litestar, get
from pathlib import Path
@get("/user/{username:str}")
def show_user_profile(username: str) -> str:
return f"User {username}"
@get("/post/{post_id:int}")
def show_post(post_id: int) -> str:
return f"Post {post_id}"
@get("/path/{subpath:path}")
def show_subpath(subpath: Path) -> str:
return f"Subpath {subpath}"
app = Litestar([show_user_profile, show_post, show_subpath])
.. seealso::
To learn more about path parameters, check out this chapter
in the documentation:
* :doc:`/usage/routing/parameters`
Request object
~~~~~~~~~~~~~~
In Flask, the current request can be accessed through a global ``request`` variable. In Litestar,
the request can be accessed through an optional parameter in the handler function.
.. tab-set::
.. tab-item:: Flask
:sync: flask
.. code-block:: python
from flask import Flask, request
app = Flask(__name__)
@app.get("/")
def index():
print(request.method)
.. tab-item:: Litestar
:sync: litestar
.. code-block:: python
from litestar import Litestar, get, Request
@get("/")
def index(request: Request) -> None:
print(request.method)
Request methods
^^^^^^^^^^^^^^^
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| Flask | Litestar |
+=================================+=======================================================================================================+
| ``request.args`` | ``request.query_params`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.base_url`` | ``request.base_url`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.authorization`` | ``request.auth`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.cache_control`` | ``request.headers.get("cache-control")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.content_encoding`` | ``request.headers.get("content-encoding")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.content_length`` | ``request.headers.get("content-length")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.content_md5`` | :octicon:`dash` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.content_type`` | ``request.content_type`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.cookies`` | ``request.cookies`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.data`` | ``request.body()`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.date`` | ``request.headers.get("date")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.endpoint`` | ``request.route_handler`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.environ`` | ``request.scope`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.files`` | Use ``UploadFile`` see in :doc:`/usage/requests` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.form`` | ``request.form()``, prefer ``Body`` see in :doc:`/usage/requests` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.get_json`` | ``request.json()``, prefer the ``data`` keyword argument, see in :doc:`/usage/requests` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.headers`` | ``request.headers`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.host`` | :octicon:`dash` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.host_url`` | :octicon:`dash` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.if_match`` | ``request.headers.get("if-match")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.if_modified_since`` | ``request.headers.get("if_modified_since")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.if_none_match`` | ``request.headers.get("if_none_match")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.if_range`` | ``request.headers.get("if_range")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.if_unmodified_since`` | ``request.headers.get("if_unmodified_since")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.method`` | ``request.method`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.mimetype`` | :octicon:`dash` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.mimetype_params`` | :octicon:`dash` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.origin`` | :octicon:`dash` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.path`` | ``request.scope["path"]`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.query_string`` | ``request.scope["query_string"]`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.range`` | ``request.headers.get("range")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.referrer`` | ``request.headers.get("referrer")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.remote_addr`` | :octicon:`dash` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.remote_user`` | :octicon:`dash` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.root_path`` | ``request.scope["root_path"]`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.server`` | ``request.scope["server"]`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.stream`` | ``request.stream`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.url`` | ``request.url`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.url_charset`` | :octicon:`dash` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.user_agent`` | ``request.headers.get("user-agent")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
| ``request.user_agent`` | ``request.headers.get("user-agent")`` |
+---------------------------------+-------------------------------------------------------------------------------------------------------+
.. seealso::
To learn more about requests, check out these chapters in the documentation
* :doc:`/usage/requests`
* :doc:`/reference/connection`
Static files
~~~~~~~~~~~~
Like Flask, Litestar also has capabilities for serving static files, but while Flask
will automatically serve files from a ``static`` folder, this has to be configured explicitly
in Litestar.
.. code-block:: python
from litestar import Litestar
from litestar.static_files import create_static_files_router
app = Litestar(route_handlers=[
create_static_files_router(path="/static", directories=["assets"]),
])
.. seealso::
To learn more about static files, check out this chapter in the documentation
* :doc:`/usage/static-files`
Templates
~~~~~~~~~
Flask comes with the `Jinja <https://jinja.palletsprojects.com/en/3.1.x/>`_ templating
engine built-in. You can use Jinja with Litestar as well, but you’ll need to install it
explicitly. You can do by installing Litestar with ``pip install 'litestar[jinja]'``.
In addition to Jinja, Litestar supports `Mako <https://www.makotemplates.org/>`_ and `Minijinja <https://github.com/mitsuhiko/minijinja/tree/main/minijinja-py>`_ templates as well.
.. tab-set::
.. tab-item:: Flask
:sync: flask
.. code-block:: python
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/hello/<name>")
def hello(name):
return render_template("hello.html", name=name)
.. tab-item:: Litestar
:sync: litestar
.. code-block:: python
from litestar import Litestar, get
from litestar.contrib.jinja import JinjaTemplateEngine
from litestar.response import Template
from litestar.template.config import TemplateConfig
@get("/hello/{name:str}")
def hello(name: str) -> Template:
return Template(response_name="hello.html", context={"name": name})
app = Litestar(
[hello],
template_config=TemplateConfig(directory="templates", engine=JinjaTemplateEngine),
)
.. seealso::
To learn more about templates, check out this chapter in the documentation:
* :doc:`/usage/templating`
Setting cookies and headers
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. tab-set::
.. tab-item:: Flask
:sync: flask
.. code-block:: python
from flask import Flask, make_response
app = Flask(__name__)
@app.get("/")
def index():
response = make_response("hello")
response.set_cookie("my-cookie", "cookie-value")
response.headers["my-header"] = "header-value"
return response
.. tab-item:: Litestar
:sync: litestar
.. code-block:: python
from litestar import Litestar, get, Response
from litestar.datastructures import ResponseHeader, Cookie
@get(
"/static",
response_headers={"my-header": ResponseHeader(value="header-value")},
response_cookies=[Cookie("my-cookie", "cookie-value")],
)
def static() -> str:
# you can set headers and cookies when defining handlers
...
@get("/dynamic")
def dynamic() -> Response[str]:
# or dynamically, by returning an instance of Response
return Response(
"hello",
headers={"my-header": "header-value"},
cookies=[Cookie("my-cookie", "cookie-value")],
)
.. seealso::
To learn more about response headers and cookies, check out these chapters in the
documentation:
- :ref:`Responses - Setting Response Headers <usage/responses:setting response headers>`
- :ref:`Responses - Setting Response Cookies <usage/responses:setting response cookies>`
Redirects
~~~~~~~~~
For redirects, instead of ``redirect`` use ``Redirect``:
.. tab-set::
.. tab-item:: Flask
:sync: flask
.. code-block:: python
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.get("/")
def index():
return "hello"
@app.get("/hello")
def hello():
return redirect(url_for("index"))
.. tab-item:: Litestar
:sync: litestar
.. code-block:: python
from litestar import Litestar, get
from litestar.response import Redirect
@get("/")
def index() -> str:
return "hello"
@get("/hello")
def hello() -> Redirect:
return Redirect(path="/")
app = Litestar([index, hello])
Raising HTTP errors
~~~~~~~~~~~~~~~~~~~
Instead of using the ``abort`` function, raise an ``HTTPException``:
.. tab-set::
.. tab-item:: Flask
:sync: flask
.. code-block:: python
from flask import Flask, abort
app = Flask(__name__)
@app.get("/")
def index():
abort(400, "this did not work")
.. tab-item:: Litestar
:sync: litestar
.. code-block:: python
from litestar import Litestar, get
from litestar.exceptions import HTTPException
@get("/")
def index() -> None:
raise HTTPException(status_code=400, detail="this did not work")
app = Litestar([index])
.. seealso::
To learn more about exceptions, check out this chapter in the documentation:
* :doc:`/usage/exceptions`
Setting status codes
~~~~~~~~~~~~~~~~~~~~
.. tab-set::
.. tab-item:: Flask
:sync: flask
.. code-block:: python
from flask import Flask
app = Flask(__name__)
@app.get("/")
def index():
return "not found", 404
.. tab-item:: Litestar
:sync: litestar
.. code-block:: python
from litestar import Litestar, get, Response
@get("/static", status_code=404)
def static_status() -> str:
return "not found"
@get("/dynamic")
def dynamic_status() -> Response[str]:
return Response("not found", status_code=404)
app = Litestar([static_status, dynamic_status])
Serialization
~~~~~~~~~~~~~
Flask uses a mix of explicit conversion (such as ``jsonify``) and inference (i.e. the type
of the returned data) to determine how data should be serialized. Litestar instead assumes
the data returned is intended to be serialized into JSON and will do so unless told otherwise.
.. tab-set::
.. tab-item:: Flask
:sync: flask
.. code-block:: python
from flask import Flask, Response
app = Flask(__name__)
@app.get("/json")
def get_json():
return {"hello": "world"}
@app.get("/text")
def get_text():
return "hello, world!"
@app.get("/html")
def get_html():
return Response("<strong>hello, world</strong>", mimetype="text/html")
.. tab-item:: Litestar
:sync: litestar
.. code-block:: python
from litestar import Litestar, get, MediaType
@get("/json")
def get_json() -> dict[str, str]:
return {"hello": "world"}
@get("/text", media_type=MediaType.TEXT)
def get_text() -> str:
return "hello, world"
@get("/html", media_type=MediaType.HTML)
def get_html() -> str:
return "<strong>hello, world</strong>"
app = Litestar([get_json, get_text, get_html])
Error handling
~~~~~~~~~~~~~~
.. tab-set::
.. tab-item:: Flask
:sync: flask
.. code-block:: python
from flask import Flask
from werkzeug.exceptions import HTTPException
app = Flask(__name__)
@app.errorhandler(HTTPException)
def handle_exception(e): ...
.. tab-item:: Litestar
:sync: litestar
.. code-block:: python
from litestar import Litestar, Request, Response
from litestar.exceptions import HTTPException
def handle_exception(request: Request, exception: Exception) -> Response: ...
app = Litestar([], exception_handlers={HTTPException: handle_exception})
.. seealso::
To learn more about exception handling, check out this chapter in the documentation:
* :ref:`usage/exceptions:exception handling`
|