-
Notifications
You must be signed in to change notification settings - Fork 329
/
Copy pathforms.py
183 lines (151 loc) · 6.91 KB
/
forms.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
from __future__ import annotations as _annotations
import enum
from collections import defaultdict
from datetime import date
from typing import Annotated, Literal, TypeAlias
from fastapi import APIRouter, Request, UploadFile
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.events import GoToEvent, PageEvent
from fastui.forms import FormFile, SelectSearchResponse, Textarea, fastui_form
from httpx import AsyncClient
from pydantic import BaseModel, EmailStr, Field, SecretStr, field_validator
from pydantic_core import PydanticCustomError
from .shared import demo_page
router = APIRouter()
@router.get('/search', response_model=SelectSearchResponse)
async def search_view(request: Request, q: str) -> SelectSearchResponse:
path_ends = f'name/{q}' if q else 'all'
client: AsyncClient = request.app.state.httpx_client
r = await client.get(f'https://restcountries.com/v3.1/{path_ends}')
if r.status_code == 404:
options = []
else:
r.raise_for_status()
data = r.json()
if path_ends == 'all':
# if we got all, filter to the 20 most populous countries
data.sort(key=lambda x: x['population'], reverse=True)
data = data[0:20]
data.sort(key=lambda x: x['name']['common'])
regions = defaultdict(list)
for co in data:
regions[co['region']].append({'value': co['cca3'], 'label': co['name']['common']})
options = [{'label': k, 'options': v} for k, v in regions.items()]
return SelectSearchResponse(options=options)
FormKind: TypeAlias = Literal['login', 'select', 'big']
@router.get('/{kind}', response_model=FastUI, response_model_exclude_none=True)
def forms_view(kind: FormKind) -> list[AnyComponent]:
return demo_page(
c.LinkList(
links=[
c.Link(
components=[c.Text(text='Login Form')],
on_click=PageEvent(name='change-form', push_path='/forms/login', context={'kind': 'login'}),
active='/forms/login',
),
c.Link(
components=[c.Text(text='Select Form')],
on_click=PageEvent(name='change-form', push_path='/forms/select', context={'kind': 'select'}),
active='/forms/select',
),
c.Link(
components=[c.Text(text='Big Form')],
on_click=PageEvent(name='change-form', push_path='/forms/big', context={'kind': 'big'}),
active='/forms/big',
),
],
mode='tabs',
class_name='+ mb-4',
),
c.ServerLoad(
path='/forms/content/{kind}',
load_trigger=PageEvent(name='change-form'),
components=form_content(kind),
),
title='Forms',
)
@router.get('/content/{kind}', response_model=FastUI, response_model_exclude_none=True)
def form_content(kind: FormKind):
match kind:
case 'login':
return [
c.Heading(text='Login Form', level=2),
c.Paragraph(text='Simple login form with email and password.'),
c.ModelForm(model=LoginForm, display_mode='page', submit_url='/api/forms/login'),
]
case 'select':
return [
c.Heading(text='Select Form', level=2),
c.Paragraph(text='Form showing different ways of doing select.'),
c.ModelForm(model=SelectForm, display_mode='page', submit_url='/api/forms/select'),
]
case 'big':
return [
c.Heading(text='Large Form', level=2),
c.Paragraph(text='Form with a lot of fields.'),
c.ModelForm(model=BigModel, display_mode='page', submit_url='/api/forms/big'),
]
case _:
raise ValueError(f'Invalid kind {kind!r}')
class LoginForm(BaseModel):
email: EmailStr = Field(title='Email Address', description="Try 'x@y' to trigger server side validation")
password: SecretStr
@router.post('/login', response_model=FastUI, response_model_exclude_none=True)
async def login_form_post(form: Annotated[LoginForm, fastui_form(LoginForm)]):
print(form)
return [c.FireEvent(event=GoToEvent(url='/'))]
class ToolEnum(str, enum.Enum):
hammer = 'hammer'
screwdriver = 'screwdriver'
saw = 'saw'
claw_hammer = 'claw_hammer'
class SelectForm(BaseModel):
select_single: ToolEnum = Field(title='Select Single')
select_multiple: list[ToolEnum] = Field(title='Select Multiple')
search_select_single: str = Field(json_schema_extra={'search_url': '/api/forms/search'})
search_select_multiple: list[str] = Field(json_schema_extra={'search_url': '/api/forms/search'})
@field_validator('select_multiple', 'search_select_multiple', mode='before')
@classmethod
def correct_select_multiple(cls, v: list[str]) -> list[str]:
if isinstance(v, list):
return v
else:
return [v]
@router.post('/select', response_model=FastUI, response_model_exclude_none=True)
async def select_form_post(form: Annotated[SelectForm, fastui_form(SelectForm)]):
# print(form)
return [c.FireEvent(event=GoToEvent(url='/'))]
class SizeModel(BaseModel):
width: int = Field(description='This is a field of a nested model')
height: int = Field(description='This is a field of a nested model')
class BigModel(BaseModel):
name: str | None = Field(
None, description='This field is not required, it must start with a capital letter if provided'
)
info: Annotated[str | None, Textarea(rows=5)] = Field(None, description='Optional free text information about you.')
repo: str = Field(json_schema_extra={'placeholder': '{org}/{repo}'}, title='GitHub repository')
profile_pic: Annotated[UploadFile, FormFile(accept='image/*', max_size=16_000)] = Field(
description='Upload a profile picture, must not be more than 16kb'
)
profile_pics: Annotated[list[UploadFile], FormFile(accept='image/*')] | None = Field(
None, description='Upload multiple images'
)
dob: date = Field(title='Date of Birth', description='Your date of birth, this is required hence bold')
human: bool | None = Field(
None, title='Is human', description='Are you human?', json_schema_extra={'mode': 'switch'}
)
size: SizeModel
position: tuple[
Annotated[int, Field(description='X Coordinate')],
Annotated[int, Field(description='Y Coordinate')],
]
@field_validator('name')
def name_validator(cls, v: str | None) -> str:
if v and v[0].islower():
raise PydanticCustomError('lower', 'Name must start with a capital letter')
return v
@router.post('/big', response_model=FastUI, response_model_exclude_none=True)
async def big_form_post(form: Annotated[BigModel, fastui_form(BigModel)]):
print(form)
return [c.FireEvent(event=GoToEvent(url='/'))]