python-fasthtml 0.14.25__tar.gz → 0.14.27__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {python_fasthtml-0.14.25/python_fasthtml.egg-info → python_fasthtml-0.14.27}/PKG-INFO +1 -2
  2. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/__init__.py +3 -2
  3. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/proxy.py +8 -3
  4. python_fasthtml-0.14.27/fasthtml/vite.py +83 -0
  5. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/pyproject.toml +1 -4
  6. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27/python_fasthtml.egg-info}/PKG-INFO +1 -2
  7. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/python_fasthtml.egg-info/SOURCES.txt +3 -1
  8. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/python_fasthtml.egg-info/requires.txt +0 -1
  9. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/tests/test_fh.py +9 -2
  10. python_fasthtml-0.14.27/tests/test_vite.py +29 -0
  11. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/CONTRIBUTING.md +0 -0
  12. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/LICENSE +0 -0
  13. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/MANIFEST.in +0 -0
  14. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/README.md +0 -0
  15. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/_modidx.py +0 -0
  16. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/authmw.py +0 -0
  17. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/basics.py +0 -0
  18. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/cli.py +0 -0
  19. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/common.py +0 -0
  20. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/components.py +0 -0
  21. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/components.pyi +0 -0
  22. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/core.py +0 -0
  23. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/core.pyi +0 -0
  24. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/fastapp.py +0 -0
  25. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/ft.py +0 -0
  26. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/js.py +0 -0
  27. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/jupyter.py +0 -0
  28. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/katex.js +0 -0
  29. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/live_reload.py +0 -0
  30. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/oauth.py +0 -0
  31. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/pico.py +0 -0
  32. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/skill.py +0 -0
  33. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/starlette.py +0 -0
  34. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/stripe_otp.py +0 -0
  35. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/svg.py +0 -0
  36. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/toaster.py +0 -0
  37. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/xtend.py +0 -0
  38. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/fasthtml/xtend.pyi +0 -0
  39. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/python_fasthtml.egg-info/dependency_links.txt +0 -0
  40. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/python_fasthtml.egg-info/entry_points.txt +0 -0
  41. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/python_fasthtml.egg-info/top_level.txt +0 -0
  42. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/setup.cfg +0 -0
  43. {python_fasthtml-0.14.25 → python_fasthtml-0.14.27}/tests/test_proxy.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-fasthtml
3
- Version: 0.14.25
3
+ Version: 0.14.27
4
4
  Summary: The fastest way to create an HTML app
5
5
  Author-email: Jeremy Howard and contributors <github@jhoward.fastmail.fm>
6
6
  License-Expression: Apache-2.0
@@ -32,7 +32,6 @@ Requires-Dist: pysym2md>=0.0.6; extra == "dev"
32
32
  Requires-Dist: monsterui; extra == "dev"
33
33
  Requires-Dist: PyJWT; extra == "dev"
34
34
  Requires-Dist: fastlite; extra == "dev"
35
- Requires-Dist: pytest-asyncio; extra == "dev"
36
35
  Dynamic: license-file
37
36
 
38
37
  # FastHTML
@@ -4,7 +4,8 @@ Modules:
4
4
 
5
5
  - `fasthtml.core`: The `FastHTML` subclass of `Starlette`.
6
6
  - `fasthtml.proxy`: Streaming HTTP responses and bidirectional WebSocket forwarding
7
- - `fasthtml.skill`: Write and review idiomatic FastHTML apps."""
7
+ - `fasthtml.skill`: Write and review idiomatic FastHTML apps.
8
+ - `fasthtml.vite`: Vite+ asset headers and development server integration for FastHTML"""
8
9
 
9
- __version__ = "0.14.25"
10
+ __version__ = "0.14.27"
10
11
  from .core import *
@@ -56,10 +56,15 @@ class ProxyResponse(Response):
56
56
  self.fallback = fallback
57
57
 
58
58
  async def __call__(self, scope, receive, send):
59
+ stream = self.request.stream()
60
+ first = await anext(stream)
61
+ async def body():
62
+ yield first
63
+ async for chunk in stream: yield chunk
59
64
  try:
60
65
  async with httpx2.AsyncClient(timeout=httpx2.Timeout(None, connect=10)) as client:
61
66
  async with client.stream(self.request.method, self.url, headers=self.fwd,
62
- params=self.request.url.query, content=self.request.stream()) as r:
67
+ params=self.request.url.query, content=body() if first else None) as r:
63
68
  response = StreamingResponse(r.aiter_raw(), status_code=r.status_code)
64
69
  replaced = {k for k,v in self.raw_headers}
65
70
  response.raw_headers = [(k,v) for k,v in proxy_headers(r.headers) if k not in replaced] + self.raw_headers
@@ -72,11 +77,11 @@ class ProxyResponse(Response):
72
77
  async def proxy_websocket(
73
78
  websocket, # Incoming Starlette WebSocket, not yet accepted
74
79
  url, # Complete upstream WebSocket URL, including query parameters
75
- headers=None, # Additional upstream handshake headers
80
+ headers=None, # Additional upstream headers, as a mapping or string/byte pairs
76
81
  ):
77
82
  "Relay text and binary frames until either peer disconnects."
78
83
  try:
79
- async with websockets.connect(url, additional_headers=headers,
84
+ async with websockets.connect(url, additional_headers=httpx2.Headers(headers).multi_items(),
80
85
  subprotocols=websocket.scope['subprotocols'] or None, max_size=None) as target:
81
86
  await websocket.accept(subprotocol=target.subprotocol)
82
87
  async def to_target():
@@ -0,0 +1,83 @@
1
+ """Vite+ asset headers and development server integration for FastHTML
2
+
3
+ Import explicitly from `fasthtml.vite` rather than `fasthtml.common`. Production apps mount a built `dist/` directory and inject hashed asset tags from `.vite/manifest.json`. Development mode (`dev=True`) runs `vp dev` inside the application lifespan for hot module replacement.
4
+
5
+ ```python
6
+ from fasthtml.common import FastHTML
7
+ from fasthtml.vite import add_vite, vite_headers
8
+
9
+ app = FastHTML()
10
+ add_vite(app, directory='.')
11
+ ```
12
+ """
13
+
14
+ __all__ = ['vite_headers', 'add_vite']
15
+
16
+ import asyncio, json
17
+ from pathlib import Path
18
+ from .components import Link, Script
19
+ from .core import FastHTML, StaticImmutable
20
+
21
+ def vite_headers(
22
+ outdir, # Build directory containing `.vite/manifest.json`
23
+ entry='src/index.js', # Entry key in the Vite manifest
24
+ base='/', # Public URL prefix, matching Vite's build `base`
25
+ ):
26
+ "Read a Vite manifest and return its stylesheets, entry script, and module preloads."
27
+ manifest = json.loads((Path(outdir)/'.vite/manifest.json').read_text())
28
+ def _imported(name, seen):
29
+ for imp in manifest[name].get('imports', []):
30
+ if imp in seen: continue
31
+ seen.add(imp)
32
+ yield from _imported(imp, seen)
33
+ yield manifest[imp]
34
+
35
+ def _url(path): return f"{base.rstrip('/')}/{path.lstrip('/')}"
36
+ entry_chunk = manifest[entry]
37
+ imported = list(_imported(entry, {entry}))
38
+ css = dict.fromkeys([*entry_chunk.get('css', []), *(c for chunk in imported for c in chunk.get('css', []))])
39
+ return [
40
+ *(Link(rel='stylesheet', href=_url(p)) for p in css),
41
+ Script(type='module', src=_url(entry_chunk['file'])),
42
+ *(Link(rel='modulepreload', href=_url(chunk['file'])) for chunk in imported),
43
+ ]
44
+
45
+ def add_vite(
46
+ app:FastHTML, # FastHTML application to configure
47
+ entry_file='index.js', # Entry filename under `<dirname>/src/`
48
+ dirname='frontend', # Subdirectory holding the Vite project, also used as URL prefix
49
+ directory='.', # Base directory containing `dirname`
50
+ dev=False, # Own a localhost `vp dev` server with hot module replacement
51
+ port=5173, # Port for the `vp dev` server when `dev=True`
52
+ ):
53
+ "Configure a FastHTML app to serve Vite+ assets or own a localhost `vp dev` server."
54
+ pwd = Path(directory).resolve()/dirname
55
+ if dev:
56
+ url = f'http://127.0.0.1:{port}/{dirname}'
57
+ previous = app.router.lifespan_context
58
+ async def lifespan(app):
59
+ proc = await asyncio.create_subprocess_exec(
60
+ 'vp', 'dev', '--host', '127.0.0.1', '--port', str(port), '--strictPort',
61
+ '--base', f'/{dirname}/', '--logLevel', 'warn', cwd=pwd)
62
+ try:
63
+ async with asyncio.timeout(10):
64
+ while True:
65
+ if proc.returncode is not None: raise RuntimeError(f'Vite exited with status {proc.returncode}')
66
+ try:
67
+ _,w = await asyncio.open_connection('127.0.0.1', port)
68
+ w.close()
69
+ await w.wait_closed()
70
+ break
71
+ except OSError: await asyncio.sleep(0.05)
72
+ app.hdrs[0:0] = [Script(type='module', src=f'{url}/@vite/client'),
73
+ Script(type='module', src=f'{url}/src/{entry_file}')]
74
+ async with previous(app) as state: yield state
75
+ finally:
76
+ if proc.returncode is None: proc.terminate()
77
+ await proc.wait()
78
+ app.set_lifespan(lifespan)
79
+ return
80
+ outdir = pwd/'dist'
81
+ app.mount(f'/{dirname}', app=StaticImmutable(directory=outdir), name=dirname)
82
+ @app.on_event('startup')
83
+ def _(): app.hdrs[0:0] = vite_headers(outdir, entry=f'src/{entry_file}', base=f'/{dirname}/')
@@ -25,7 +25,7 @@ fasthtml = "fasthtml._modidx:d"
25
25
  fasthtml = "fasthtml.skill"
26
26
 
27
27
  [project.optional-dependencies]
28
- dev = ['ipython', 'lxml', 'pysym2md>=0.0.6', 'monsterui', 'PyJWT', 'fastlite', 'pytest-asyncio']
28
+ dev = ['ipython', 'lxml', 'pysym2md>=0.0.6', 'monsterui', 'PyJWT', 'fastlite']
29
29
 
30
30
 
31
31
  [project.scripts]
@@ -48,6 +48,3 @@ lib_path = "fasthtml"
48
48
  [tool.chkstyle]
49
49
  skip_paths = ["_modidx.py"]
50
50
  ignore = ["closing-bracket", "inefficient-multiline-signature", "inefficient-multiline-expression"]
51
-
52
- [tool.pytest.ini_options]
53
- asyncio_default_fixture_loop_scope = 'function'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-fasthtml
3
- Version: 0.14.25
3
+ Version: 0.14.27
4
4
  Summary: The fastest way to create an HTML app
5
5
  Author-email: Jeremy Howard and contributors <github@jhoward.fastmail.fm>
6
6
  License-Expression: Apache-2.0
@@ -32,7 +32,6 @@ Requires-Dist: pysym2md>=0.0.6; extra == "dev"
32
32
  Requires-Dist: monsterui; extra == "dev"
33
33
  Requires-Dist: PyJWT; extra == "dev"
34
34
  Requires-Dist: fastlite; extra == "dev"
35
- Requires-Dist: pytest-asyncio; extra == "dev"
36
35
  Dynamic: license-file
37
36
 
38
37
  # FastHTML
@@ -27,6 +27,7 @@ fasthtml/starlette.py
27
27
  fasthtml/stripe_otp.py
28
28
  fasthtml/svg.py
29
29
  fasthtml/toaster.py
30
+ fasthtml/vite.py
30
31
  fasthtml/xtend.py
31
32
  fasthtml/xtend.pyi
32
33
  python_fasthtml.egg-info/PKG-INFO
@@ -36,4 +37,5 @@ python_fasthtml.egg-info/entry_points.txt
36
37
  python_fasthtml.egg-info/requires.txt
37
38
  python_fasthtml.egg-info/top_level.txt
38
39
  tests/test_fh.py
39
- tests/test_proxy.py
40
+ tests/test_proxy.py
41
+ tests/test_vite.py
@@ -16,4 +16,3 @@ pysym2md>=0.0.6
16
16
  monsterui
17
17
  PyJWT
18
18
  fastlite
19
- pytest-asyncio
@@ -64,6 +64,7 @@ async def echo_http(request):
64
64
  response = StreamingResponse(iter([body[:1], body[1:]]), status_code=201, headers={
65
65
  'content-type': request.headers.get('content-type', 'application/octet-stream'),
66
66
  'x-query': request.url.query, 'x-method': request.method,
67
+ 'x-transfer-encoding': request.headers.get('transfer-encoding', ''),
67
68
  'x-private': request.headers.get('x-private', ''), 'x-auth': request.headers.get('authorization', '')})
68
69
  response.raw_headers += [(b'x-tag', value.encode()) for value in request.headers.getlist('x-tag')]
69
70
  return response
@@ -71,6 +72,7 @@ async def echo_http(request):
71
72
  async def echo_ws(ws):
72
73
  if status := ws.query_params.get('deny'): return await ws.send_denial_response(Response(status_code=int(status)))
73
74
  await ws.accept(subprotocol='echo')
75
+ await ws.send_text(ws.headers.get('x-api-token', ''))
74
76
  await ws.send_text(await ws.receive_text())
75
77
  await ws.send_bytes(await ws.receive_bytes())
76
78
  await ws.close(code=1000)
@@ -80,8 +82,9 @@ def test_proxy():
80
82
  with running_server(upstream) as url:
81
83
  async def forward_http(request):
82
84
  return ProxyResponse(request, url, headers=proxy_headers(request.headers, exclude=(b'authorization',)))
83
- async def forward_ws(ws): await proxy_websocket(ws, url.replace('http', 'ws')+'/ws?'+ws.url.query)
84
- app = Starlette(routes=[Route('/', forward_http, methods=['PATCH']), WebSocketRoute('/ws', forward_ws)])
85
+ async def forward_ws(ws):
86
+ await proxy_websocket(ws, url.replace('http', 'ws')+'/ws?'+ws.url.query, headers=[(b'x-api-token', b'user:key')])
87
+ app = Starlette(routes=[Route('/', forward_http, methods=['GET', 'PATCH']), WebSocketRoute('/ws', forward_ws)])
85
88
  with TestClient(app) as proxy:
86
89
  body = b'["a", {"b":2}]'
87
90
  headers = [('Content-Type', 'application/json'), ('X-Tag', 'a'), ('X-Tag', 'b'),
@@ -91,8 +94,12 @@ def test_proxy():
91
94
  assert res.headers['content-type']=='application/json' and res.headers['x-query']=='q=one&q=two'
92
95
  assert (res.headers['x-method'], res.headers['x-private'], res.headers['x-auth']) == ('PATCH', '', '')
93
96
  assert res.headers.get_list('x-tag') == ['a', 'b']
97
+ res = proxy.get('/')
98
+ assert res.content == b'' and res.headers['x-transfer-encoding'] == ''
99
+ assert proxy.request('GET', '/', content=iter([body[:1], body[1:]])).content == body
94
100
  with proxy.websocket_connect('/ws', subprotocols=['echo']) as ws:
95
101
  assert ws.accepted_subprotocol == 'echo'
102
+ assert ws.receive_text() == 'user:key'
96
103
  ws.send_text('hello')
97
104
  assert ws.receive_text() == 'hello'
98
105
  ws.send_bytes(b'\x00bytes')
@@ -0,0 +1,29 @@
1
+ import json
2
+ from fasthtml.vite import vite_headers
3
+
4
+ def test_vite_headers_transitive_dedupe_and_cycles(tmp_path):
5
+ manifest = {
6
+ 'src/index.js': dict(file='assets/index.js', css=['assets/app.css'], imports=['_a.js', '_b.js']),
7
+ '_a.js': dict(file='assets/a.js', css=['assets/shared.css', 'assets/app.css'], imports=['_shared.js', 'src/index.js']),
8
+ '_b.js': dict(file='assets/b.js', imports=['_shared.js']),
9
+ '_shared.js': dict(file='assets/shared.js', css=['assets/shared.css'], imports=['_a.js']),
10
+ 'unused.js': dict(file='assets/unused.js', css=['assets/unused.css']),
11
+ }
12
+ mdir = tmp_path/'.vite'
13
+ mdir.mkdir()
14
+ (mdir/'manifest.json').write_text(json.dumps(manifest))
15
+
16
+ hdrs = vite_headers(tmp_path, base='/frontend/')
17
+ tags = [(h.tag, h.attrs) for h in hdrs]
18
+ assert tags == [
19
+ ('link', {'rel': 'stylesheet', 'href': '/frontend/assets/app.css'}),
20
+ ('link', {'rel': 'stylesheet', 'href': '/frontend/assets/shared.css'}),
21
+ ('script', {'type': 'module', 'src': '/frontend/assets/index.js'}),
22
+ ('link', {'rel': 'modulepreload', 'href': '/frontend/assets/shared.js'}),
23
+ ('link', {'rel': 'modulepreload', 'href': '/frontend/assets/a.js'}),
24
+ ('link', {'rel': 'modulepreload', 'href': '/frontend/assets/b.js'}),
25
+ ]
26
+
27
+ rel = [h.attrs.get('href') or h.attrs.get('src') for h in vite_headers(tmp_path, base='./')]
28
+ assert rel[0] == './assets/app.css' and rel[2] == './assets/index.js'
29
+