Skip to content

Commit

Permalink
core_tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jph00 committed Jun 1, 2024
1 parent a0da762 commit 8f89639
Show file tree
Hide file tree
Showing 3 changed files with 499 additions and 938 deletions.
41 changes: 11 additions & 30 deletions fasthtml/core.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.

# %% auto 0
__all__ = ['empty', 'htmx_hdrs', 'htmxscr', 'all_meths', 'is_namedtuple', 'date', 'snake2hyphens', 'HtmxHeaders', 'str2int',
'HttpHeader', 'RouteX', 'RouterX', 'get_key', 'FastHTML', 'reg_re_param']

# %% ../nbs/00_core.ipynb 2
import json, dateutil, uuid

from fastcore.utils import *
Expand All @@ -20,22 +16,22 @@

from .starlette import *

# %% ../nbs/00_core.ipynb 4

empty = Parameter.empty

# %% ../nbs/00_core.ipynb 5
def is_namedtuple(cls):
"`True` is `cls` is a namedtuple type"
return issubclass(cls, tuple) and hasattr(cls, '_fields')

# %% ../nbs/00_core.ipynb 6
def date(s): return dateutil.parser.parse(s)
def date(s:str):
"Convert `s` to a datetime"
return dateutil.parser.parse(s)

# %% ../nbs/00_core.ipynb 7
def snake2hyphens(s):
def snake2hyphens(s:str):
"Convert `s` from snake case to hyphenated and capitalised"
s = snake2camel(s)
return camel2words(s, '-')

# %% ../nbs/00_core.ipynb 8
htmx_hdrs = dict(
boosted="HX-Boosted",
current_url="HX-Current-URL",
Expand All @@ -56,30 +52,28 @@ def _get_htmx(req):
res = {k:req.headers.get(v.lower(), None) for k,v in htmx_hdrs.items()}
return HtmxHeaders(**res)

# %% ../nbs/00_core.ipynb 9
def str2int(s)->int:
"Convert `s` to an `int`"
s = s.lower()
if s=='on': return 1
if s=='none': return 0
return 0 if not s else int(s)

# %% ../nbs/00_core.ipynb 10
def _fix_anno(t):
"Create appropriate callable type for casting a `str` to type `t` (or first type in `t` if union)"
origin = get_origin(t)
if origin is Union or origin is UnionType:
t = first(o for o in get_args(t) if o!=type(None))
d = {bool: str2bool, int: str2int}
return d.get(t, t)

# %% ../nbs/00_core.ipynb 11
def _form_arg(k, v, d):
"Get type by accessing key `k` from `d`, and use to cast `v`"
if v is None: return
anno = d.get(k, None)
if not anno: return v
return _fix_anno(anno)(v)

# %% ../nbs/00_core.ipynb 12
def _is_body(anno):
return issubclass(anno, (dict,ns)) or is_dataclass(anno) or is_namedtuple(anno) or get_annotations(anno)

Expand All @@ -97,7 +91,6 @@ async def _from_body(req, arg, p):
cargs = {k:_form_arg(k, v, d) for k,v in body.items()}
return anno(**cargs)

# %% ../nbs/00_core.ipynb 13
async def _find_p(req, arg:str, p):
anno = p.annotation
if isinstance(anno, type):
Expand All @@ -123,15 +116,12 @@ async def _find_p(req, arg:str, p):
if not isinstance(res, str) or anno is empty: return res
return _fix_anno(anno)(res)

# %% ../nbs/00_core.ipynb 14
async def _wrap_req(req, params):
return [await _find_p(req, arg, p) for arg,p in params.items()]

# %% ../nbs/00_core.ipynb 15
@dataclass
class HttpHeader: k:str;v:str

# %% ../nbs/00_core.ipynb 16
def _xt_resp(req, resp, hdrs, **bodykw):
http_hdrs,resp = partition(resp, risinstance(HttpHeader))
http_hdrs = {o.k:str(o.v) for o in http_hdrs}
Expand All @@ -140,7 +130,6 @@ def _xt_resp(req, resp, hdrs, **bodykw):
resp = Html(Header(titles[0], *hdrs), Body(bdy, **bodykw))
return HTMLResponse(to_xml(resp), headers=http_hdrs)

# %% ../nbs/00_core.ipynb 17
def _wrap_resp(req, resp, cls, hdrs, **bodykw):
if isinstance(resp, Response): return resp
if cls is not empty: return cls(resp)
Expand All @@ -152,7 +141,6 @@ def _wrap_resp(req, resp, cls, hdrs, **bodykw):
cls = HTMLResponse
return cls(resp)

# %% ../nbs/00_core.ipynb 18
def _wrap_ep(f, hdrs, **bodykw):
if not (isfunction(f) or ismethod(f)): return f
sig = signature(f)
Expand All @@ -166,14 +154,12 @@ async def _f(req):
return _wrap_resp(req, resp, cls, hdrs, **bodykw)
return _f

# %% ../nbs/00_core.ipynb 19
class RouteX(Route):
def __init__(self, path:str, endpoint, *, methods=None, name=None, include_in_schema=True, middleware=None,
hdrs=None, **bodykw):
super().__init__(path, _wrap_ep(endpoint, hdrs, **bodykw), methods=methods, name=name,
include_in_schema=include_in_schema, middleware=middleware)

# %% ../nbs/00_core.ipynb 20
class RouterX(Router):
def __init__(self, routes=None, redirect_slashes=True, default=None, on_startup=None, on_shutdown=None,
lifespan=None, *, middleware=None, hdrs=None, **bodykw):
Expand All @@ -187,12 +173,10 @@ def add_route( self, path: str, endpoint: callable, methods=None, name=None, inc
self.routes = [o for o in self.routes if o.methods!=methods or o.path!=path]
self.routes.append(route)

# %% ../nbs/00_core.ipynb 21
htmxscr = Script(
src="https://unpkg.com/htmx.org@1.9.12", crossorigin="anonymous",
integrity="sha384-ujb1lZYygJmzgSwoxRggbCHcjc0rB2XoQrxeTUQyRjrOnlCoYta87iKBWq3EsdM2")

# %% ../nbs/00_core.ipynb 22
def get_key(key=None, fname='.sesskey'):
if key: return key
fname = Path(fname)
Expand All @@ -201,7 +185,6 @@ def get_key(key=None, fname='.sesskey'):
fname.write_text(key)
return key

# %% ../nbs/00_core.ipynb 24
class FastHTML(Starlette):
def __init__(self, debug=False, routes=None, middleware=None, exception_handlers=None,
on_startup=None, on_shutdown=None, lifespan=None, hdrs=None,
Expand All @@ -224,16 +207,14 @@ def f(func):
return func
return f

# %% ../nbs/00_core.ipynb 25
all_meths = 'get post put delete patch head trace options'.split()
for o in all_meths:
setattr(FastHTML, o, partialmethod(FastHTML.route, methods=o))
for o in all_meths: setattr(FastHTML, o, partialmethod(FastHTML.route, methods=o))

# %% ../nbs/00_core.ipynb 26
def reg_re_param(m, s):
cls = get_class(f'{m}Conv', sup=StringConvertor, regex=s)
register_url_convertor(m, cls())

# Starlette doesn't have the '?', so it chomps the whole remaining URL
reg_re_param("path", ".*?")
reg_re_param("static", "ico|gif|jpg|jpeg|webm|css|js|woff|png|svg|mp4|webp|ttf|otf|eot|woff2|txt|xml")

Loading

0 comments on commit 8f89639

Please sign in to comment.