-
Notifications
You must be signed in to change notification settings - Fork 0
/
diary.py
164 lines (137 loc) · 4.59 KB
/
diary.py
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
"""Diary Application
Records date and description. Entries are displayed as a card.
It uses bootstrap 5.2.3 to style the elements.
pip install reactpy
pip install pandas
pip install reactpy-flake8
"""
from typing import Union
from datetime import datetime
from reactpy import component, html, event, hooks
from reactpy.backend.fastapi import configure, Options
from fastapi import FastAPI
import pandas as pd
BOOTSTRAP_CSS = html.link(
{
'href': 'https://cdn.jsdelivr.net/npm/'
'bootstrap@5.2.3/dist/css/bootstrap.min.css',
'integrity': 'sha384-rbsA2VBKQhggwzxH7pPCaAq'
'O46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65',
'rel': 'stylesheet',
'crossorigin': 'anonymous'
}
)
PAGE_TITLE = 'ReactPy-Diary'
CSV_FILENAME = 'diary.csv'
COLUMN_HEADER = ['Date', 'Description']
def get_df(fn: str) -> tuple[bool, Union[pd.DataFrame, str]]:
"""Converts csv file to dataframe."""
try:
df = pd.read_csv(fn)
except FileNotFoundError:
df = pd.DataFrame(columns=COLUMN_HEADER)
df.to_csv(fn, index=False)
except Exception as err:
return False, repr(err)
return True, df
def get_date() -> str:
"""Gets date and time."""
now = datetime.now()
return now.strftime("%Y-%m-%d %H:%M:%S")
@component
def Card(text: list):
return html.div(
html.div(
{'class': 'card text-dark bg-light border-secondary mb-2'},
html.div(
{'class': 'card-body text-secondary'},
html.div(
{'class': 'card-title text-secondary'},
html.h6(text[0])
),
html.div(
{'class': 'card-text text-secondary'},
html.span(f'{text[1]}'),
),
),
),
)
@component
def BuildCards(fn: str, records: list):
"""Save record to csv and build a list of cards."""
dfr = pd.DataFrame(records, columns=COLUMN_HEADER)
dfr.to_csv(fn, index=False)
return html.div(
{
'style': {
'height': '600px',
'overflow-y': 'auto',
'white-space': 'pre-wrap'
}
},
[Card(rec) for rec in records[::-1]]
)
@component
def Diary():
csvfn = CSV_FILENAME
description, set_description = hooks.use_state('')
# Open the existing csv file. It will be created if it does not exist.
# If there is error, we will send the error message and exit.
okdf, df = get_df(csvfn)
if not okdf:
return html.h4(
{'style': {'color': 'red'}},
f'There is error {df} in opening the {csvfn} file.'
)
# Initialize our records from existing csv file.
records, set_records = hooks.use_state(df.values.tolist())
def update_textvalue(event):
set_description(event['target']['value'])
@event(prevent_default=True)
def submit(event):
"""Updates records."""
set_records(records + [[get_date(), description]])
return html.div(
BOOTSTRAP_CSS,
html.div(
{'class': 'container'},
html.div(
html.h2('My Diary'),
html.form(
{'on_submit': submit},
html.div(
{'class': 'form-group'},
html.label(
{
'html_for': 'description',
'class': 'text-primary fs-5'
},
'Description'
),
html.textarea(
{
'class': 'form-control border-primary',
'id': 'description',
'type': 'textarea',
'rows': '4',
'on_change': update_textvalue,
}
),
),
html.p(),
html.input(
{'class': 'btn btn-success',
'type': 'submit', 'value': 'Save'}
),
html.input(
{'class': 'btn btn-danger mx-1',
'type': 'reset', 'value': 'Clear'}
),
),
html.p(),
BuildCards(csvfn, records),
),
),
)
app = FastAPI()
configure(app, Diary, options=Options(head=html.head(html.title(PAGE_TITLE))))