-
Notifications
You must be signed in to change notification settings - Fork 0
/
example-app.py
69 lines (44 loc) · 1.76 KB
/
example-app.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
from pathlib import Path
from pydantic import BaseSettings, validator
from starlite.app import Starlite
from starlite.controller import Controller
from starlite.enums import MediaType
from starlite.exceptions import NotFoundException
from starlite.handlers import get
from starlite_react import ReactController
"""
This example uses Pydantic to configure the app using environment variables.
Run example-app.py using Poetry and Uvicorn:
# point this variable to the build directory of any React app
export REACT_DIRECTORY="~/tests/react-build"
poetry run uvicorn --reload example-app:app
"""
_dir = Path(__file__).parent
class Settings(BaseSettings):
react_directory: Path = _dir / "tests/react-build"
@validator("react_directory")
def validate_react_directory(cls, v: Path) -> Path:
assert v.is_dir(), f"directory does not exist: {v}"
return v
settings = Settings()
class ApiController(Controller):
path = "/api"
@get(media_type=MediaType.TEXT)
def api_root(self) -> str:
return "Hello, World!"
@get(path="/{_:path}")
def not_found(self) -> None:
raise NotFoundException()
class AppReactController(ReactController):
"""
Subclass ReactController and set the `directory` field
"""
directory = settings.react_directory
"""
The ReactController is going to own its url path -- even if it is root (which it is by default).
Any unspecified route will return the React index instead of throwing a 404. This allows React Router DOM
to work without Starlite interfering.
In this example, ApiController has a catch-all route which will properly throw a 404 if a
non-existant API call is attempted within its path (/api).
"""
app = Starlite(route_handlers=[AppReactController, ApiController])