-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllm.txt
3041 lines (2391 loc) · 122 KB
/
llm.txt
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<project title="FastHTML" summary='FastHTML is a python library which brings together Starlette, Uvicorn, HTMX, and fastcore's `FT` "FastTags" into a library for creating server-rendered hypermedia applications. The `FastHTML` class itself inherits from `Starlette`, and adds decorator-based routing with many additions, Beforeware, automatic `FT` to HTML rendering, and much more.'>Things to remember when writing FastHTML apps:
- Although parts of its API are inspired by FastAPI, it is *not* compatible with FastAPI syntax and is not targeted at creating API services
- FastHTML includes support for Pico CSS and the fastlite sqlite library, although using both are optional; sqlalchemy can be used directly or via the fastsql library, and any CSS framework can be used. Support for the Surreal and css-scope-inline libraries are also included, but both are optional
- FastHTML is compatible with JS-native web components and any vanilla JS library, but not with React, Vue, or Svelte
- Use `serve()` for running uvicorn (`if __name__ == "__main__"` is not needed since it's automatic)
- When a title is needed with a response, use `Titled`; note that that already wraps children in `Container`, and already includes both the meta title as well as the H1 element.<docs><doc title="FastHTML quick start" desc="A brief overview of many FastHTML features"># Web Devs Quickstart
## Installation
``` bash
pip install python-fasthtml
```
## A Minimal Application
A minimal FastHTML application looks something like this:
<div class="code-with-filename">
**main.py**
``` python
from fasthtml.common import *
app, rt = fast_app()
@rt("/")
def get():
return Titled("FastHTML", P("Let's do this!"))
serve()
```
</div>
Line 1
We import what we need for rapid development! A carefully-curated set of
FastHTML functions and other Python objects is brought into our global
namespace for convenience.
Line 3
We instantiate a FastHTML app with the `fast_app()` utility function.
This provides a number of really useful defaults that we’ll take
advantage of later in the tutorial.
Line 5
We use the `rt()` decorator to tell FastHTML what to return when a user
visits `/` in their browser.
Line 6
We connect this route to HTTP GET requests by defining a view function
called `get()`.
Line 7
A tree of Python function calls that return all the HTML required to
write a properly formed web page. You’ll soon see the power of this
approach.
Line 9
The `serve()` utility configures and runs FastHTML using a library
called `uvicorn`.
Run the code:
``` bash
python main.py
```
The terminal will look like this:
``` bash
INFO: Uvicorn running on http://0.0.0.0:5001 (Press CTRL+C to quit)
INFO: Started reloader process [58058] using WatchFiles
INFO: Started server process [58060]
INFO: Waiting for application startup.
INFO: Application startup complete.
```
Confirm FastHTML is running by opening your web browser to
[127.0.0.1:5001](http://127.0.0.1:5001). You should see something like
the image below:

<div>
> **Note**
>
> While some linters and developers will complain about the wildcard
> import, it is by design here and perfectly safe. FastHTML is very
> deliberate about the objects it exports in `fasthtml.common`. If it
> bothers you, you can import the objects you need individually, though
> it will make the code more verbose and less readable.
>
> If you want to learn more about how FastHTML handles imports, we cover
> that [here](https://docs.fastht.ml/explains/faq.html#why-use-import).
</div>
## A Minimal Charting Application
The
[`Script`](https://AnswerDotAI.github.io/fasthtml/api/xtend.html#script)
function allows you to include JavaScript. You can use Python to
generate parts of your JS or JSON like this:
``` python
import json
from fasthtml.common import *
app, rt = fast_app(hdrs=(Script(src="https://cdn.plot.ly/plotly-2.32.0.min.js"),))
data = json.dumps({
"data": [{"x": [1, 2, 3, 4],"type": "scatter"},
{"x": [1, 2, 3, 4],"y": [16, 5, 11, 9],"type": "scatter"}],
"title": "Plotly chart in FastHTML ",
"description": "This is a demo dashboard",
"type": "scatter"
})
@rt("/")
def get():
return Titled("Chart Demo", Div(id="myDiv"),
Script(f"var data = {data}; Plotly.newPlot('myDiv', data);"))
serve()
```
## Debug Mode
When we can’t figure out a bug in FastHTML, we can run it in `DEBUG`
mode. When an error is thrown, the error screen is displayed in the
browser. This error setting should never be used in a deployed app.
``` python
from fasthtml.common import *
app, rt = fast_app(debug=True)
@rt("/")
def get():
1/0
return Titled("FastHTML Error!", P("Let's error!"))
serve()
```
Line 3
`debug=True` sets debug mode on.
Line 7
Python throws an error when it tries to divide an integer by zero.
## Routing
FastHTML builds upon FastAPI’s friendly decorator pattern for specifying
URLs, with extra features:
<div class="code-with-filename">
**main.py**
``` python
from fasthtml.common import *
app, rt = fast_app()
@rt("/")
def get():
return Titled("FastHTML", P("Let's do this!"))
@rt("/hello")
def get():
return Titled("Hello, world!")
serve()
```
</div>
Line 5
The “/” URL on line 5 is the home of a project. This would be accessed
at [127.0.0.1:5001](http://127.0.0.1:5001).
Line 9
“/hello” URL on line 9 will be found by the project if the user visits
[127.0.0.1:5001/hello](http://127.0.0.1:5001/hello).
<div>
> **Tip**
>
> It looks like `get()` is being defined twice, but that’s not the case.
> Each function decorated with `rt` is totally separate, and is injected
> into the router. We’re not calling them in the module’s namespace
> (`locals()`). Rather, we’re loading them into the routing mechanism
> using the `rt` decorator.
</div>
You can do more! Read on to learn what we can do to make parts of the
URL dynamic.
## Variables in URLs
You can add variable sections to a URL by marking them with
`{variable_name}`. Your function then receives the `{variable_name}` as
a keyword argument, but only if it is the correct type. Here’s an
example:
<div class="code-with-filename">
**main.py**
``` python
from fasthtml.common import *
app, rt = fast_app()
@rt("/{name}/{age}")
def get(name: str, age: int):
return Titled(f"Hello {name.title()}, age {age}")
serve()
```
</div>
Line 5
We specify two variable names, `name` and `age`.
Line 6
We define two function arguments named identically to the variables. You
will note that we specify the Python types to be passed.
Line 7
We use these functions in our project.
Try it out by going to this address:
[127.0.0.1:5001/uma/5](http://127.0.0.1:5001/uma/5). You should get a
page that says,
> “Hello Uma, age 5”.
### What happens if we enter incorrect data?
The [127.0.0.1:5001/uma/5](http://127.0.0.1:5001/uma/5) URL works
because `5` is an integer. If we enter something that is not, such as
[127.0.0.1:5001/uma/five](http://127.0.0.1:5001/uma/five), then FastHTML
will return an error instead of a web page.
<div>
> **FastHTML URL routing supports more complex types**
>
> The two examples we provide here use Python’s built-in `str` and `int`
> types, but you can use your own types, including more complex ones
> such as those defined by libraries like
> [attrs](https://pypi.org/project/attrs/),
> [pydantic](https://pypi.org/project/pydantic/), and even
> [sqlmodel](https://pypi.org/project/sqlmodel/).
</div>
## HTTP Methods
FastHTML matches function names to HTTP methods. So far the URL routes
we’ve defined have been for HTTP GET methods, the most common method for
web pages.
Form submissions often are sent as HTTP POST. When dealing with more
dynamic web page designs, also known as Single Page Apps (SPA for
short), the need can arise for other methods such as HTTP PUT and HTTP
DELETE. The way FastHTML handles this is by changing the function name.
<div class="code-with-filename">
**main.py**
``` python
from fasthtml.common import *
app, rt = fast_app()
@rt("/")
def get():
return Titled("HTTP GET", P("Handle GET"))
@rt("/")
def post():
return Titled("HTTP POST", P("Handle POST"))
serve()
```
</div>
Line 6
On line 6 because the `get()` function name is used, this will handle
HTTP GETs going to the `/` URI.
Line 10
On line 10 because the `post()` function name is used, this will handle
HTTP POSTs going to the `/` URI.
## CSS Files and Inline Styles
Here we modify default headers to demonstrate how to use the [Sakura CSS
microframework](https://github.com/oxalorg/sakura) instead of FastHTML’s
default of Pico CSS.
<div class="code-with-filename">
**main.py**
``` python
from fasthtml.common import *
app, rt = fast_app(
pico=False,
hdrs=(
Link(rel='stylesheet', href='assets/normalize.min.css', type='text/css'),
Link(rel='stylesheet', href='assets/sakura.css', type='text/css'),
Style("p {color: red;}")
))
@app.get("/")
def home():
return Titled("FastHTML",
P("Let's do this!"),
)
serve()
```
</div>
Line 4
By setting `pico` to `False`, FastHTML will not include `pico.min.css`.
Line 7
This will generate an HTML `<link>` tag for sourcing the css for Sakura.
Line 8
If you want an inline styles, the `Style()` function will put the result
into the HTML.
## Other Static Media File Locations
As you saw,
[`Script`](https://AnswerDotAI.github.io/fasthtml/api/xtend.html#script)
and `Link` are specific to the most common static media use cases in web
apps: including JavaScript, CSS, and images. But it also works with
videos and other static media files. The default behavior is to look for
these files in the root directory - typically we don’t do anything
special to include them. We can change the default directory that is
looked in for files by adding the `static_path` parameter to the
[`fast_app`](https://AnswerDotAI.github.io/fasthtml/api/fastapp.html#fast_app)
function.
``` python
app, rt = fast_app(static_path='public')
```
FastHTML also allows us to define a route that uses `FileResponse` to
serve the file at a specified path. This is useful for serving images,
videos, and other media files from a different directory without having
to change the paths of many files. So if we move the directory
containing the media files, we only need to change the path in one
place. In the example below, we call images from a directory called
`public`.
``` python
@rt("/{fname:path}.{ext:static}")
async def get(fname:str, ext:str):
return FileResponse(f'public/{fname}.{ext}')
```
## Rendering Markdown
``` python
from fasthtml.common import *
hdrs = (MarkdownJS(), HighlightJS(langs=['python', 'javascript', 'html', 'css']), )
app, rt = fast_app(hdrs=hdrs)
content = """
Here are some _markdown_ elements.
- This is a list item
- This is another list item
- And this is a third list item
**Fenced code blocks work here.**
"""
@rt('/')
def get(req):
return Titled("Markdown rendering example", Div(content,cls="marked"))
serve()
```
## Code highlighting
Here’s how to highlight code without any markdown configuration.
``` python
from fasthtml.common import *
# Add the HighlightJS built-in header
hdrs = (HighlightJS(langs=['python', 'javascript', 'html', 'css']),)
app, rt = fast_app(hdrs=hdrs)
code_example = """
import datetime
import time
for i in range(10):
print(f"{datetime.datetime.now()}")
time.sleep(1)
"""
@rt('/')
def get(req):
return Titled("Markdown rendering example",
Div(
# The code example needs to be surrounded by
# Pre & Code elements
Pre(Code(code_example))
))
serve()
```
## Defining new `ft` components
We can build our own `ft` components and combine them with other
components. The simplest method is defining them as a function.
``` python
from fasthtml.common import *
```
``` python
def hero(title, statement):
return Div(H1(title),P(statement), cls="hero")
# usage example
Main(
hero("Hello World", "This is a hero statement")
)
```
``` html
<main>
<div class="hero">
<h1>Hello World</h1>
<p>This is a hero statement</p>
</div>
</main>
```
### Pass through components
For when we need to define a new component that allows zero-to-many
components to be nested within them, we lean on Python’s `*args` and
`**kwargs` mechanism. Useful for creating page layout controls.
``` python
def layout(*args, **kwargs):
"""Dashboard layout for all our dashboard views"""
return Main(
H1("Dashboard"),
Div(*args, **kwargs),
cls="dashboard",
)
# usage example
layout(
Ul(*[Li(o) for o in range(3)]),
P("Some content", cls="description"),
)
```
``` html
<main class="dashboard">
<h1>Dashboard</h1>
<div>
<ul>
<li>0</li>
<li>1</li>
<li>2</li>
</ul>
<p class="description">Some content</p>
</div>
</main>
```
### Dataclasses as ft components
While functions are easy to read, for more complex components some might
find it easier to use a dataclass.
``` python
from dataclasses import dataclass
@dataclass
class Hero:
title: str
statement: str
def __ft__(self):
""" The __ft__ method renders the dataclass at runtime."""
return Div(H1(self.title),P(self.statement), cls="hero")
# usage example
Main(
Hero("Hello World", "This is a hero statement")
)
```
``` html
<main>
<div class="hero">
<h1>Hello World</h1>
<p>This is a hero statement</p>
</div>
</main>
```
## Testing views in notebooks
Because of the ASGI event loop it is currently impossible to run
FastHTML inside a notebook. However, we can still test the output of our
views. To do this, we leverage Starlette, an ASGI toolkit that FastHTML
uses.
``` python
# First we instantiate our app, in this case we remove the
# default headers to reduce the size of the output.
app, rt = fast_app(default_hdrs=False)
# Setting up the Starlette test client
from starlette.testclient import TestClient
client = TestClient(app)
# Usage example
@rt("/")
def get():
return Titled("FastHTML is awesome",
P("The fastest way to create web apps in Python"))
print(client.get("/").text)
```
<!doctype html>
<html>
<head>
<title>FastHTML is awesome</title>
</head>
<body>
<main class="container">
<h1>FastHTML is awesome</h1>
<p>The fastest way to create web apps in Python</p>
</main>
</body>
</html>
## Forms
To validate data coming from users, first define a dataclass
representing the data you want to check. Here’s an example representing
a signup form.
``` python
from dataclasses import dataclass
@dataclass
class Profile: email:str; phone:str; age:int
```
Create an FT component representing an empty version of that form. Don’t
pass in any value to fill the form, that gets handled later.
``` python
profile_form = Form(method="post", action="/profile")(
Fieldset(
Label('Email', Input(name="email")),
Label("Phone", Input(name="phone")),
Label("Age", Input(name="age")),
),
Button("Save", type="submit"),
)
profile_form
```
``` html
<form enctype="multipart/form-data" method="post" action="/profile">
<fieldset>
<label>
Email
<input name="email">
</label>
<label>
Phone
<input name="phone">
</label>
<label>
Age
<input name="age">
</label>
</fieldset>
<button type="submit">Save</button>
</form>
```
Once the dataclass and form function are completed, we can add data to
the form. To do that, instantiate the profile dataclass:
``` python
profile = Profile(email='john@example.com', phone='123456789', age=5)
profile
```
Profile(email='john@example.com', phone='123456789', age=5)
Then add that data to the `profile_form` using FastHTML’s
[`fill_form`](https://AnswerDotAI.github.io/fasthtml/api/components.html#fill_form)
class:
``` python
fill_form(profile_form, profile)
```
``` html
<form enctype="multipart/form-data" method="post" action="/profile">
<fieldset>
<label>
Email
<input name="email" value="john@example.com">
</label>
<label>
Phone
<input name="phone" value="123456789">
</label>
<label>
Age
<input name="age" value="5">
</label>
</fieldset>
<button type="submit">Save</button>
</form>
```
### Forms with views
The usefulness of FastHTML forms becomes more apparent when they are
combined with FastHTML views. We’ll show how this works by using the
test client from above. First, let’s create a SQlite database:
``` python
db = Database("profiles.db")
profiles = db.create(Profile, pk="email")
```
Now we insert a record into the database:
``` python
profiles.insert(profile)
```
Profile(email='john@example.com', phone='123456789', age=5)
And we can then demonstrate in the code that form is filled and
displayed to the user.
``` python
@rt("/profile/{email}")
def profile(email:str):
profile = profiles[email]
filled_profile_form = fill_form(profile_form, profile)
return Titled(f'Profile for {profile.email}', filled_profile_form)
print(client.get(f"/profile/john@example.com").text)
```
Line 3
Fetch the profile using the profile table’s `email` primary key
Line 4
Fill the form for display.
<!doctype html>
<html>
<head>
<title>Profile for john@example.com</title>
</head>
<body>
<main class="container">
<h1>Profile for john@example.com</h1>
<form enctype="multipart/form-data" method="post" action="/profile">
<fieldset>
<label>
Email
<input name="email" value="john@example.com">
</label>
<label>
Phone
<input name="phone" value="123456789">
</label>
<label>
Age
<input name="age" value="5">
</label>
</fieldset>
<button type="submit">Save</button>
</form>
</main>
</body>
</html>
And now let’s demonstrate making a change to the data.
``` python
@rt("/profile")
def post(profile: Profile):
profiles.update(profile)
return RedirectResponse(url=f"/profile/{profile.email}")
new_data = dict(email='john@example.com', phone='7654321', age=25)
print(client.post("/profile", data=new_data).text)
```
Line 2
We use the `Profile` dataclass definition to set the type for the
incoming `profile` content. This validates the field types for the
incoming data
Line 3
Taking our validated data, we updated the profiles table
Line 4
We redirect the user back to their profile view
Line 7
The display is of the profile form view showing the changes in data.
<!doctype html>
<html>
<head>
<title>Profile for john@example.com</title>
</head>
<body>
<main class="container">
<h1>Profile for john@example.com</h1>
<form enctype="multipart/form-data" method="post" action="/profile">
<fieldset>
<label>
Email
<input name="email" value="john@example.com">
</label>
<label>
Phone
<input name="phone" value="7654321">
</label>
<label>
Age
<input name="age" value="25">
</label>
</fieldset>
<button type="submit">Save</button>
</form>
</main>
</body>
</html>
## Strings and conversion order
The general rules for rendering are: - `__ft__` method will be called
(for default components like `P`, `H2`, etc. or if you define your own
components) - If you pass a string, it will be escaped - On other python
objects, `str()` will be called
As a consequence, if you want to include plain HTML tags directly into
e.g. a `Div()` they will get escaped by default (as a security measure
to avoid code injections). This can be avoided by using `NotStr()`, a
convenient way to reuse python code that returns already HTML. If you
use pandas, you can use `pandas.DataFrame.to_html()` to get a nice
table. To include the output a FastHTML, wrap it in `NotStr()`, like
`Div(NotStr(df.to_html()))`.
Above we saw how a dataclass behaves with the `__ft__` method defined.
On a plain dataclass, `str()` will be called (but not escaped).
``` python
from dataclasses import dataclass
@dataclass
class Hero:
title: str
statement: str
# rendering the dataclass with the default method
Main(
Hero("<h1>Hello World</h1>", "This is a hero statement")
)
```
``` html
<main>Hero(title='<h1>Hello World</h1>', statement='This is a hero statement')</main>
```
``` python
# This will display the HTML as text on your page
Div("Let's include some HTML here: <div>Some HTML</div>")
```
``` html
<div>Let's include some HTML here: <div>Some HTML</div></div>
```
``` python
# Keep the string untouched, will be rendered on the page
Div(NotStr("<div><h1>Some HTML</h1></div>"))
```
``` html
<div><div><h1>Some HTML</h1></div></div>
```
## Custom exception handlers
FastHTML allows customization of exception handlers, but does so
gracefully. What this means is by default it includes all the `<html>`
tags needed to display attractive content. Try it out!
``` python
from fasthtml.common import *
def not_found(req, exc): return Titled("404: I don't exist!")
exception_handlers = {404: not_found}
app, rt = fast_app(exception_handlers=exception_handlers)
@rt('/')
def get():
return (Titled("Home page", P(A(href="/oops")("Click to generate 404 error"))))
serve()
```
We can also use lambda to make things more terse:
``` python
from fasthtml.common import *
exception_handlers={
404: lambda req, exc: Titled("404: I don't exist!"),
418: lambda req, exc: Titled("418: I'm a teapot!")
}
app, rt = fast_app(exception_handlers=exception_handlers)
@rt('/')
def get():
return (Titled("Home page", P(A(href="/oops")("Click to generate 404 error"))))
serve()
```
## Cookies
We can set cookies using the `cookie()` function. In our example, we’ll
create a `timestamp` cookie.
``` python
from datetime import datetime
from IPython.display import HTML
```
``` python
@rt("/settimestamp")
def get(req):
now = datetime.now()
return P(f'Set to {now}'), cookie('now', datetime.now())
HTML(client.get('/settimestamp').text)
```
<!doctype html>
<html>
<head>
<title>FastHTML page</title>
</head>
<body>
<p>Set to 2024-09-04 18:30:34.896373</p>
</body>
</html>
Now let’s get it back using the same name for our parameter as the
cookie name.
``` python
@rt('/gettimestamp')
def get(now:parsed_date): return f'Cookie was set at time {now.time()}'
client.get('/gettimestamp').text
```
'Cookie was set at time 18:30:34.896405'
## Sessions
For convenience and security, FastHTML has a mechanism for storing small
amounts of data in the user’s browser. We can do this by adding a
`session` argument to routes. FastHTML sessions are Python dictionaries,
and we can leverage to our benefit. The example below shows how to
concisely set and get sessions.
``` python
@rt('/adder/{num}')
def get(session, num: int):
session.setdefault('sum', 0)
session['sum'] = session.get('sum') + num
return Response(f'The sum is {session["sum"]}.')
```
## Toasts (also known as Messages)
Toasts, sometimes called “Messages” are small notifications usually in
colored boxes used to notify users that something has happened. Toasts
can be of four types:
- info
- success
- warning
- error
Examples toasts might include:
- “Payment accepted”
- “Data submitted”
- “Request approved”
Toasts require the use of the `setup_toasts()` function plus every view
needs these two features:
- The session argument
- Must return FT components
``` python
setup_toasts(app)
@rt('/toasting')
def get(session):
# Normally one toast is enough, this allows us to see
# different toast types in action.
add_toast(session, f"Toast is being cooked", "info")
add_toast(session, f"Toast is ready", "success")
add_toast(session, f"Toast is getting a bit crispy", "warning")
add_toast(session, f"Toast is burning!", "error")
return Titled("I like toast")
```
Line 1
`setup_toasts` is a helper function that adds toast dependencies.
Usually this would be declared right after `fast_app()`
Line 4
Toasts require sessions
Line 11
Views with Toasts must return FT components.
## Authentication and authorization
In FastHTML the tasks of authentication and authorization are handled
with Beforeware. Beforeware are functions that run before the route
handler is called. They are useful for global tasks like ensuring users
are authenticated or have permissions to access a view.
First, we write a function that accepts a request and session arguments:
``` python
# Status code 303 is a redirect that can change POST to GET,
# so it's appropriate for a login page.
login_redir = RedirectResponse('/login', status_code=303)