python-fasthtml 0.14.21__tar.gz → 0.14.22__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 (42) hide show
  1. {python_fasthtml-0.14.21/python_fasthtml.egg-info → python_fasthtml-0.14.22}/PKG-INFO +3 -1
  2. python_fasthtml-0.14.22/fasthtml/__init__.py +9 -0
  3. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/_modidx.py +5 -0
  4. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/core.py +23 -4
  5. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/oauth.py +3 -3
  6. python_fasthtml-0.14.22/fasthtml/proxy.py +100 -0
  7. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/pyproject.toml +5 -2
  8. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22/python_fasthtml.egg-info}/PKG-INFO +3 -1
  9. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/python_fasthtml.egg-info/SOURCES.txt +3 -1
  10. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/python_fasthtml.egg-info/requires.txt +2 -0
  11. python_fasthtml-0.14.22/tests/test_fh.py +99 -0
  12. python_fasthtml-0.14.22/tests/test_proxy.py +0 -0
  13. python_fasthtml-0.14.21/fasthtml/__init__.py +0 -8
  14. python_fasthtml-0.14.21/tests/test_toaster.py +0 -63
  15. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/CONTRIBUTING.md +0 -0
  16. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/LICENSE +0 -0
  17. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/MANIFEST.in +0 -0
  18. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/README.md +0 -0
  19. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/authmw.py +0 -0
  20. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/basics.py +0 -0
  21. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/cli.py +0 -0
  22. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/common.py +0 -0
  23. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/components.py +0 -0
  24. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/components.pyi +0 -0
  25. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/core.pyi +0 -0
  26. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/fastapp.py +0 -0
  27. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/ft.py +0 -0
  28. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/js.py +0 -0
  29. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/jupyter.py +0 -0
  30. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/katex.js +0 -0
  31. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/live_reload.py +0 -0
  32. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/pico.py +0 -0
  33. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/starlette.py +0 -0
  34. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/stripe_otp.py +0 -0
  35. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/svg.py +0 -0
  36. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/toaster.py +0 -0
  37. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/xtend.py +0 -0
  38. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/fasthtml/xtend.pyi +0 -0
  39. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/python_fasthtml.egg-info/dependency_links.txt +0 -0
  40. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/python_fasthtml.egg-info/entry_points.txt +0 -0
  41. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/python_fasthtml.egg-info/top_level.txt +0 -0
  42. {python_fasthtml-0.14.21 → python_fasthtml-0.14.22}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-fasthtml
3
- Version: 0.14.21
3
+ Version: 0.14.22
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
@@ -22,6 +22,7 @@ Requires-Dist: oauthlib
22
22
  Requires-Dist: itsdangerous
23
23
  Requires-Dist: uvicorn[standard]>=0.30
24
24
  Requires-Dist: httpx2
25
+ Requires-Dist: websockets>=14
25
26
  Requires-Dist: python-multipart
26
27
  Requires-Dist: beautifulsoup4
27
28
  Provides-Extra: dev
@@ -31,6 +32,7 @@ Requires-Dist: pysym2md>=0.0.6; extra == "dev"
31
32
  Requires-Dist: monsterui; extra == "dev"
32
33
  Requires-Dist: PyJWT; extra == "dev"
33
34
  Requires-Dist: fastlite; extra == "dev"
35
+ Requires-Dist: pytest-asyncio; extra == "dev"
34
36
  Dynamic: license-file
35
37
 
36
38
  # FastHTML
@@ -0,0 +1,9 @@
1
+ """The fastest way to create an HTML app
2
+
3
+ Modules:
4
+
5
+ - `fasthtml.core`: The `FastHTML` subclass of `Starlette`.
6
+ - `fasthtml.proxy`: Streaming HTTP responses and bidirectional WebSocket forwarding"""
7
+
8
+ __version__ = "0.14.22"
9
+ from .core import *
@@ -35,6 +35,11 @@ d = { 'settings': { 'branch': 'main',
35
35
  'fasthtml.core.ApiReturn.__call__': ('api/core.html#apireturn.__call__', 'fasthtml/core.py'),
36
36
  'fasthtml.core.ApiReturn.__from_request__': ('api/core.html#apireturn.__from_request__', 'fasthtml/core.py'),
37
37
  'fasthtml.core.ApiReturn.__init__': ('api/core.html#apireturn.__init__', 'fasthtml/core.py'),
38
+ 'fasthtml.core.BearerSessionMiddleware': ('api/core.html#bearersessionmiddleware', 'fasthtml/core.py'),
39
+ 'fasthtml.core.BearerSessionMiddleware.__call__': ( 'api/core.html#bearersessionmiddleware.__call__',
40
+ 'fasthtml/core.py'),
41
+ 'fasthtml.core.BearerSessionMiddleware.__init__': ( 'api/core.html#bearersessionmiddleware.__init__',
42
+ 'fasthtml/core.py'),
38
43
  'fasthtml.core.Beforeware': ('api/core.html#beforeware', 'fasthtml/core.py'),
39
44
  'fasthtml.core.Beforeware.__init__': ('api/core.html#beforeware.__init__', 'fasthtml/core.py'),
40
45
  'fasthtml.core.Beforeware.__repr__': ('api/core.html#beforeware.__repr__', 'fasthtml/core.py'),
@@ -49,10 +49,10 @@ __all__ = ['empty', 'htmx_hdrs', 'fh_cfg', 'htmx_resps', 'DEF_MAXPART', 'htmx_ex
49
49
  'scopesrc', 'viewport', 'charset', 'cors_allow', 'iframe_scr', 'all_meths', 'devtools_loc', 'parsed_date',
50
50
  'snake2hyphens', 'HtmxHeaders', 'HttpHeader', 'HtmxResponseHeaders', 'form2dict', 'parse_form', 'ApiReturn',
51
51
  'JSONResponse', 'flat_xt', 'Beforeware', 'EventStream', 'signal_shutdown', 'uri', 'decode_uri', 'flat_tuple',
52
- 'noop_body', 'respond', 'is_full_page', 'Redirect', 'get_key', 'qp', 'def_hdrs', 'Lifespan', 'FastHTML',
53
- 'HostRoute', 'nested_name', 'serve', 'until_disconnect', 'cancel_on_disconnect', 'Client', 'RouteFuncs',
54
- 'APIRouter', 'cookie', 'reg_re_param', 'StaticNoCache', 'StaticImmutable', 'vurl', 'add_sig_param', 'into',
55
- 'MiddlewareBase', 'FtResponse', 'unqid']
52
+ 'noop_body', 'respond', 'is_full_page', 'Redirect', 'get_key', 'qp', 'def_hdrs', 'Lifespan',
53
+ 'BearerSessionMiddleware', 'FastHTML', 'HostRoute', 'nested_name', 'serve', 'until_disconnect',
54
+ 'cancel_on_disconnect', 'Client', 'RouteFuncs', 'APIRouter', 'cookie', 'reg_re_param', 'StaticNoCache',
55
+ 'StaticImmutable', 'vurl', 'add_sig_param', 'into', 'MiddlewareBase', 'FtResponse', 'unqid']
56
56
 
57
57
  # %% ../nbs/api/00_core.ipynb #23503b9e
58
58
  import json,uuid,inspect,types,asyncio,inspect,random,contextlib,itsdangerous,hashlib,signal,subprocess
@@ -690,6 +690,25 @@ class Lifespan:
690
690
 
691
691
  def on_event(self, event_type): return lambda f: (getattr(self, event_type)).append(f)
692
692
 
693
+ # %% ../nbs/api/00_core.ipynb #375b0f62
694
+ class BearerSessionMiddleware(SessionMiddleware):
695
+ "Accept signed session cookies through Authorization within `bearer_path`."
696
+ @delegates(SessionMiddleware)
697
+ def __init__(self, app, secret_key, bearer_path='/', **kwargs):
698
+ self.bearer_path = bearer_path
699
+ super().__init__(app, secret_key, **kwargs)
700
+
701
+ async def __call__(self, scope, receive, send):
702
+ if scope['type'] in ('http', 'websocket') and scope['path'].startswith(self.bearer_path):
703
+ conn = HTTPConnection(scope)
704
+ if 'authorization' in conn.headers:
705
+ scheme, _, token = conn.headers['authorization'].partition(' ')
706
+ value = cookies.SimpleCookie().value_encode(token if scheme.lower()=='bearer' else '')[1]
707
+ cookie = '; '.join(conn.headers.getlist('cookie') + [f'{self.session_cookie}={value}'])
708
+ scope = scope | dict(headers=[(k,v) for k,v in scope['headers'] if k!=b'cookie'] +
709
+ [(b'cookie', cookie.encode('latin-1'))])
710
+ await super().__call__(scope, receive, send)
711
+
693
712
  # %% ../nbs/api/00_core.ipynb #3327a1e9
694
713
  class FastHTML(Starlette):
695
714
  "An HTML-first Starlette app: handler params filled from the request, FT returns rendered as pages or HTMX fragments"
@@ -234,11 +234,11 @@ class OAuth:
234
234
  if not skip: skip = [redir_path,error_path,login_path]
235
235
  redir_handler = app.post if redir_method == 'post' else app.get
236
236
  store_attr()
237
- async def before(req, session):
237
+ async def before(req, session, api):
238
238
  if 'auth' not in req.scope: req.scope['auth'] = session.get('auth')
239
239
  auth = req.scope['auth']
240
- if not auth: return self.redir_login(session)
241
- res = await _arun(self.check_invalid(req, session, auth))
240
+ res = self.redir_login(session) if not auth else await _arun(self.check_invalid(req, session, auth))
241
+ if api and isinstance(res, RedirectResponse): return JSONResponse({'error':'Not authenticated.'}, status_code=401)
242
242
  if res: return res
243
243
  app.before.append(Beforeware(before, skip=skip))
244
244
 
@@ -0,0 +1,100 @@
1
+ """Streaming HTTP responses and bidirectional WebSocket forwarding
2
+
3
+ Register proxy handlers with Starlette's `Route` and `WebSocketRoute`. FastHTML's normal route injection parses request bodies before calling the handler. Raw routes leave JSON, multipart and other bodies unread for forwarding. Choose the upstream URL and authenticate callers in your application.
4
+
5
+ `ProxyResponse` streams request and response bodies without decoding them. It preserves response status and end-to-end headers, including repeated headers. You can supply filtered request headers and override response headers through `response.headers`. `fallback` is an optional response for upstream connection failures. Connection attempts time out after 10 seconds. Transfers have no timeout.
6
+
7
+ Connection-nominated headers and explicitly excluded names are removed. Repeated end-to-end values remain separate, with lowercase names.
8
+
9
+ `proxy_websocket` connects upstream before accepting the caller. It forwards the selected subprotocol and relays text and binary frames. Either peer disconnecting cancels the other forwarding task and closes the upstream connection. Supply a complete URL, including any query parameters.
10
+
11
+ The relay reads raw ASGI events from `receive()`. A `websocket.receive` event carries `text` or `bytes`. A `websocket.disconnect` event carries a close `code`. `receive_text()` and `receive_bytes()` extract one data field instead.
12
+
13
+ Register raw routes after any application routes that should take precedence. Keep access checks and destination selection in these handlers.
14
+
15
+ ```python
16
+ from fasthtml.common import FastHTML
17
+ from fasthtml.proxy import ProxyResponse, proxy_websocket
18
+ from starlette.routing import Route, WebSocketRoute
19
+
20
+ app = FastHTML()
21
+ async def forward_http(request): return ProxyResponse(request, 'http://127.0.0.1:8000/')
22
+ async def forward_ws(ws): await proxy_websocket(ws, 'ws://127.0.0.1:8000/ws')
23
+ app.router.routes += [Route('/upstream', forward_http, methods=['GET', 'POST', 'PATCH']),
24
+ WebSocketRoute('/upstream/ws', forward_ws)]
25
+ ```
26
+ """
27
+
28
+ __all__ = ['proxy_headers', 'ProxyResponse', 'proxy_websocket']
29
+
30
+ import asyncio, httpx2, websockets
31
+ from starlette.responses import Response, StreamingResponse
32
+
33
+ def proxy_headers(
34
+ headers, # Starlette or HTTPX headers exposing `.raw` pairs
35
+ exclude=(), # Additional lowercase byte names to remove
36
+ ):
37
+ "Remove hop-by-hop headers before forwarding."
38
+ hop = {b'host', b'connection', b'keep-alive', b'proxy-authenticate', b'proxy-authorization',
39
+ b'te', b'trailer', b'transfer-encoding', b'upgrade'}
40
+ hop.update(v.strip().encode() for v in headers.get('connection', '').lower().split(','))
41
+ return [(k.lower(),v) for k,v in headers.raw if k.lower() not in hop and k.lower() not in exclude]
42
+
43
+ class ProxyResponse(Response):
44
+ "Stream a request and response while keeping their transport open."
45
+ def __init__(
46
+ self,
47
+ request, # Incoming Starlette request
48
+ url, # Upstream URL without query parameters
49
+ headers=None, # Upstream request headers; default removes hop-by-hop fields
50
+ fallback=None, # Optional ASGI response for upstream connection failures
51
+ ):
52
+ super().__init__()
53
+ self.raw_headers = []
54
+ self.request,self.url = request,url
55
+ self.fwd = proxy_headers(request.headers) if headers is None else headers
56
+ self.fallback = fallback
57
+
58
+ async def __call__(self, scope, receive, send):
59
+ try:
60
+ async with httpx2.AsyncClient(timeout=httpx2.Timeout(None, connect=10)) as client:
61
+ async with client.stream(self.request.method, self.url, headers=self.fwd,
62
+ params=self.request.url.query, content=self.request.stream()) as r:
63
+ response = StreamingResponse(r.aiter_raw(), status_code=r.status_code)
64
+ replaced = {k for k,v in self.raw_headers}
65
+ response.raw_headers = [(k,v) for k,v in proxy_headers(r.headers) if k not in replaced] + self.raw_headers
66
+ await response(scope, receive, send)
67
+ except (httpx2.ConnectError, httpx2.ConnectTimeout):
68
+ if self.fallback is None: raise
69
+ await self.fallback(scope, receive, send)
70
+
71
+
72
+ async def proxy_websocket(
73
+ websocket, # Incoming Starlette WebSocket, not yet accepted
74
+ url, # Complete upstream WebSocket URL, including query parameters
75
+ headers=None, # Additional upstream handshake headers
76
+ ):
77
+ "Relay text and binary frames until either peer disconnects."
78
+ async with websockets.connect(url, additional_headers=headers,
79
+ subprotocols=websocket.scope['subprotocols'], max_size=None) as target:
80
+ await websocket.accept(subprotocol=target.subprotocol)
81
+ async def to_target():
82
+ while True:
83
+ message = await websocket.receive()
84
+ if message['type']=='websocket.disconnect': return
85
+ await target.send(message['text'] if 'text' in message else message['bytes'])
86
+ async def to_client():
87
+ async for message in target:
88
+ if isinstance(message, str): await websocket.send_text(message)
89
+ else: await websocket.send_bytes(message)
90
+ tasks = [asyncio.create_task(to_target()), asyncio.create_task(to_client())]
91
+ try:
92
+ done,_ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
93
+ for task in done: task.result()
94
+ finally:
95
+ for task in tasks: task.cancel()
96
+ await asyncio.gather(*tasks, return_exceptions=True)
97
+ if websocket.client_state.name!='DISCONNECTED':
98
+ code = target.close_code if target.close_code not in (None, 1005, 1006, 1015) else 1011
99
+ await websocket.close(code=code, reason=target.close_reason or '')
100
+
@@ -12,7 +12,7 @@ license = "Apache-2.0"
12
12
  authors = [{name = "Jeremy Howard and contributors", email = "github@jhoward.fastmail.fm"}]
13
13
  keywords = ['nbdev', 'jupyter', 'notebook', 'python']
14
14
  classifiers = ["Natural Language :: English", "Intended Audience :: Developers", "Development Status :: 3 - Alpha", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only"]
15
- dependencies = ['fastcore>=2.2.7', 'python-dateutil', 'starlette>=1.0.1', 'oauthlib', 'itsdangerous', 'uvicorn[standard]>=0.30', 'httpx2', 'python-multipart', 'beautifulsoup4']
15
+ dependencies = ['fastcore>=2.2.7', 'python-dateutil', 'starlette>=1.0.1', 'oauthlib', 'itsdangerous', 'uvicorn[standard]>=0.30', 'httpx2', 'websockets>=14', 'python-multipart', 'beautifulsoup4']
16
16
 
17
17
  [project.urls]
18
18
  Repository = "https://github.com/AnswerDotAI/fasthtml"
@@ -22,7 +22,7 @@ Documentation = "https://www.fastht.ml/docs/"
22
22
  fasthtml = "fasthtml._modidx:d"
23
23
 
24
24
  [project.optional-dependencies]
25
- dev = ['ipython', 'lxml', 'pysym2md>=0.0.6', 'monsterui', 'PyJWT', 'fastlite']
25
+ dev = ['ipython', 'lxml', 'pysym2md>=0.0.6', 'monsterui', 'PyJWT', 'fastlite', 'pytest-asyncio']
26
26
 
27
27
 
28
28
  [project.scripts]
@@ -45,3 +45,6 @@ lib_path = "fasthtml"
45
45
  [tool.chkstyle]
46
46
  skip_paths = ["_modidx.py"]
47
47
  ignore = ["closing-bracket", "inefficient-multiline-signature", "inefficient-multiline-expression"]
48
+
49
+ [tool.pytest.ini_options]
50
+ 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.21
3
+ Version: 0.14.22
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
@@ -22,6 +22,7 @@ Requires-Dist: oauthlib
22
22
  Requires-Dist: itsdangerous
23
23
  Requires-Dist: uvicorn[standard]>=0.30
24
24
  Requires-Dist: httpx2
25
+ Requires-Dist: websockets>=14
25
26
  Requires-Dist: python-multipart
26
27
  Requires-Dist: beautifulsoup4
27
28
  Provides-Extra: dev
@@ -31,6 +32,7 @@ Requires-Dist: pysym2md>=0.0.6; extra == "dev"
31
32
  Requires-Dist: monsterui; extra == "dev"
32
33
  Requires-Dist: PyJWT; extra == "dev"
33
34
  Requires-Dist: fastlite; extra == "dev"
35
+ Requires-Dist: pytest-asyncio; extra == "dev"
34
36
  Dynamic: license-file
35
37
 
36
38
  # FastHTML
@@ -21,6 +21,7 @@ fasthtml/katex.js
21
21
  fasthtml/live_reload.py
22
22
  fasthtml/oauth.py
23
23
  fasthtml/pico.py
24
+ fasthtml/proxy.py
24
25
  fasthtml/starlette.py
25
26
  fasthtml/stripe_otp.py
26
27
  fasthtml/svg.py
@@ -33,4 +34,5 @@ python_fasthtml.egg-info/dependency_links.txt
33
34
  python_fasthtml.egg-info/entry_points.txt
34
35
  python_fasthtml.egg-info/requires.txt
35
36
  python_fasthtml.egg-info/top_level.txt
36
- tests/test_toaster.py
37
+ tests/test_fh.py
38
+ tests/test_proxy.py
@@ -5,6 +5,7 @@ oauthlib
5
5
  itsdangerous
6
6
  uvicorn[standard]>=0.30
7
7
  httpx2
8
+ websockets>=14
8
9
  python-multipart
9
10
  beautifulsoup4
10
11
 
@@ -15,3 +16,4 @@ pysym2md>=0.0.6
15
16
  monsterui
16
17
  PyJWT
17
18
  fastlite
19
+ pytest-asyncio
@@ -0,0 +1,99 @@
1
+ from fasthtml.common import *
2
+ from starlette.testclient import TestClient
3
+ import httpx2, socket, uvicorn
4
+ from fasthtml.proxy import ProxyResponse, proxy_headers, proxy_websocket
5
+ from contextlib import contextmanager
6
+ from threading import Thread
7
+ from starlette.applications import Starlette
8
+ from starlette.routing import Route, WebSocketRoute
9
+ from starlette.responses import StreamingResponse
10
+
11
+
12
+ app, rt = fast_app()
13
+ setup_toasts(app)
14
+
15
+ @rt("/set-toast-get")
16
+ def get(session):
17
+ add_toast(session, "Toast get", "info")
18
+ return RedirectResponse('/see-toast')
19
+
20
+ @rt("/set-toast-post")
21
+ def post(session):
22
+ add_toast(session, "Toast post", "info")
23
+ return RedirectResponse('/see-toast')
24
+
25
+ @rt("/see-toast")
26
+ def get(session): return Titled("Hello, world!")
27
+
28
+ @rt("/see-toast-with-typehint")
29
+ def get(session: dict): return Titled("Hello, world!")
30
+
31
+ @rt("/see-toast-ft-response")
32
+ def get(session):
33
+ add_toast(session, "Toast FtResponse", "info")
34
+ return FtResponse(Titled("Hello, world!"))
35
+
36
+ def test_toasts():
37
+ with TestClient(app) as cli:
38
+ cli.get('/set-toast-get', follow_redirects=False)
39
+ assert 'Toast get' in cli.get('/see-toast-with-typehint').text
40
+ assert 'Toast get' not in cli.get('/see-toast').text
41
+ cli.post('/set-toast-post', follow_redirects=False)
42
+ assert 'Toast post' in cli.get('/see-toast').text
43
+ res = cli.get('/see-toast-ft-response')
44
+ assert 'Toast FtResponse' in res.text
45
+ assert 'id="fh-toast-container"' in res.text
46
+
47
+ @contextmanager
48
+ def running_server(app):
49
+ with socket.create_server(('127.0.0.1', 0)) as sock:
50
+ server = uvicorn.Server(uvicorn.Config(app, port=0, log_level='error'))
51
+ thread = Thread(target=server.run, kwargs=dict(sockets=[sock]), daemon=True)
52
+ thread.start()
53
+ url = f'http://127.0.0.1:{sock.getsockname()[1]}'
54
+ try:
55
+ httpx2.get(url, timeout=5).raise_for_status()
56
+ yield url
57
+ finally:
58
+ server.should_exit = True
59
+ thread.join(5)
60
+ assert not thread.is_alive()
61
+
62
+ async def echo_http(request):
63
+ body = await request.body()
64
+ response = StreamingResponse(iter([body[:1], body[1:]]), status_code=201, headers={
65
+ 'content-type': request.headers.get('content-type', 'application/octet-stream'),
66
+ 'x-query': request.url.query, 'x-method': request.method,
67
+ 'x-private': request.headers.get('x-private', ''), 'x-auth': request.headers.get('authorization', '')})
68
+ response.raw_headers += [(b'x-tag', value.encode()) for value in request.headers.getlist('x-tag')]
69
+ return response
70
+
71
+ async def echo_ws(ws):
72
+ await ws.accept(subprotocol='echo')
73
+ await ws.send_text(await ws.receive_text())
74
+ await ws.send_bytes(await ws.receive_bytes())
75
+ await ws.close(code=1000)
76
+
77
+ def test_proxy():
78
+ upstream = Starlette(routes=[Route('/', echo_http, methods=['GET', 'PATCH']), WebSocketRoute('/ws', echo_ws)])
79
+ with running_server(upstream) as url:
80
+ async def forward_http(request):
81
+ return ProxyResponse(request, url, headers=proxy_headers(request.headers, exclude=(b'authorization',)))
82
+ async def forward_ws(ws): await proxy_websocket(ws, url.replace('http', 'ws')+'/ws')
83
+ app = Starlette(routes=[Route('/', forward_http, methods=['PATCH']), WebSocketRoute('/ws', forward_ws)])
84
+ with TestClient(app) as proxy:
85
+ body = b'["a", {"b":2}]'
86
+ headers = [('Content-Type', 'application/json'), ('X-Tag', 'a'), ('X-Tag', 'b'),
87
+ ('Connection', 'x-private'), ('X-Private', 'internal'), ('Authorization', 'private')]
88
+ res = proxy.patch('/?q=one&q=two', content=body, headers=headers)
89
+ assert (res.status_code, res.content) == (201, body)
90
+ assert res.headers['content-type']=='application/json' and res.headers['x-query']=='q=one&q=two'
91
+ assert (res.headers['x-method'], res.headers['x-private'], res.headers['x-auth']) == ('PATCH', '', '')
92
+ assert res.headers.get_list('x-tag') == ['a', 'b']
93
+ with proxy.websocket_connect('/ws', subprotocols=['echo']) as ws:
94
+ assert ws.accepted_subprotocol == 'echo'
95
+ ws.send_text('hello')
96
+ assert ws.receive_text() == 'hello'
97
+ ws.send_bytes(b'\x00bytes')
98
+ assert ws.receive_bytes() == b'\x00bytes'
99
+ assert ws.receive()['code'] == 1000
File without changes
@@ -1,8 +0,0 @@
1
- """The fastest way to create an HTML app
2
-
3
- Modules:
4
-
5
- - `fasthtml.core`: The `FastHTML` subclass of `Starlette`."""
6
-
7
- __version__ = "0.14.21"
8
- from .core import *
@@ -1,63 +0,0 @@
1
- from fasthtml.common import *
2
- from starlette.testclient import TestClient
3
-
4
- app, rt = fast_app()
5
- setup_toasts(app)
6
- cli = TestClient(app)
7
-
8
- @rt("/set-toast-get")
9
- def get(session):
10
- add_toast(session, "Toast get", "info")
11
- return RedirectResponse('/see-toast')
12
-
13
- @rt("/set-toast-post")
14
- def post(session):
15
- add_toast(session, "Toast post", "info")
16
- return RedirectResponse('/see-toast')
17
-
18
- @rt("/see-toast")
19
- def get(session):
20
- return Titled("Hello, world!", P(str(session)))
21
-
22
- @rt("/see-toast-with-typehint")
23
- def get(session: dict):
24
- return Titled("Hello, world!", P(str(session)))
25
-
26
- @rt("/see-toast-ft-response")
27
- def get(session):
28
- add_toast(session, "Toast FtResponse", "info")
29
- return FtResponse(Titled("Hello, world!", P(str(session))))
30
-
31
- def test_get_toaster():
32
- cli.get('/set-toast-get', follow_redirects=False)
33
- res = cli.get('/see-toast')
34
- assert 'Toast get' in res.text
35
-
36
- res = cli.get('/set-toast-get', follow_redirects=True)
37
- assert 'Toast get' in res.text
38
-
39
- def test_post_toaster():
40
- cli.post('/set-toast-post', follow_redirects=False)
41
- res = cli.get('/see-toast')
42
- assert 'Toast post' in res.text
43
-
44
- def test_ft_response():
45
- res = cli.get('/see-toast-ft-response')
46
- assert 'Toast FtResponse' in res.text
47
-
48
- def test_get_toaster_with_typehint():
49
- res = cli.get('/see-toast-with-typehint', follow_redirects=False)
50
- assert 'Toast get' in res.text
51
-
52
- res = cli.get('/see-toast-with-typehint', follow_redirects=True)
53
- assert 'Toast get' in res.text
54
-
55
- def test_toast_container_in_response():
56
- # toasts will not render correctly if the toast container isn't rendered.
57
- res = cli.get('/see-toast-ft-response')
58
- assert 'id="fh-toast-container"' in res.text
59
-
60
- test_get_toaster()
61
- test_post_toaster()
62
- test_ft_response()
63
- test_toast_container_in_response()