python-fasthtml 0.0.2__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ include settings.ini
2
+ include LICENSE
3
+ include CONTRIBUTING.md
4
+ include README.md
5
+ recursive-exclude * __pycache__
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.1
2
+ Name: python-fasthtml
3
+ Version: 0.0.2
4
+ Summary: The fastest way to create an HTML app
5
+ Home-page: https://github.com/AnswerDotAI/fasthtml
6
+ Author: Jeremy Howard
7
+ Author-email: github@jhoward.fastmail.fm
8
+ License: Apache Software License 2.0
9
+ Keywords: nbdev jupyter notebook python
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: fastcore
19
+ Requires-Dist: python-dateutil
20
+ Requires-Dist: starlette
21
+ Provides-Extra: dev
22
+ Requires-Dist: httpx; extra == "dev"
23
+ Requires-Dist: ipython; extra == "dev"
24
+
25
+ # fasthtml
26
+
27
+
28
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
29
+
30
+ `fasthtml` is a library for writing fast and scalable Starlette-powered
31
+ web applications, without having to learn much (if any!) Starlette.
32
+ Instead, you just use plain python functions for each page in your app –
33
+ you don’t even need to learn Javascript. The finished app will be about
34
+ as fast as a Python web server can be (which is pretty fast –
35
+ e.g. Instagram runs on Python), and you can create pretty much anything.
36
+ This isn’t one of those stripped-down dashboard making thingies.
37
+
38
+ This is a way to write real web applications, without the fuss.
39
+
40
+ To learn how to use it, please visit the
41
+ [documentation](https://answerdotai.github.io/fasthtml/).
42
+
43
+ ## Install
44
+
45
+ ``` sh
46
+ pip install python-fasthtml
47
+ ```
48
+
49
+ ## How to use
50
+
51
+ Import `fasthtml`, and you’ll probably want the widgets from
52
+ `fastcore.xml` too.
53
+
54
+ ``` python
55
+ from fasthtml import *
56
+ from fastcore.xml import *
57
+ ```
58
+
59
+ Create your app.
60
+
61
+ ``` python
62
+ app = FastHTML()
63
+ ```
64
+
65
+ Create your routes. The syntax is largely the same as the wonderful
66
+ [FastAPI](https://fastapi.tiangolo.com/) (which is what you should be
67
+ using instead of this if you’re creating a JSON service. FastHTML is for
68
+ mainly for making HTML web apps, not APIs).
69
+
70
+ Note that you need to include the types of your parameters, so that
71
+ [`FastHTML`](https://AnswerDotAI.github.io/fasthtml/core.html#fasthtml)
72
+ knows what to pass to your function. Here, we’re just expecting a
73
+ string:
74
+
75
+ ``` python
76
+ @app.get('/user/{nm}')
77
+ def get_nm(nm:str): return f"Good day to you, {nm}!"
78
+ ```
79
+
80
+ Normally you’d save this into a file such as main.py, and then run it in
81
+ `uvicorn` using:
82
+
83
+ uvicorn main:app
84
+
85
+ However, for testing, we can use Starlette’s `TestClient` to try it out:
86
+
87
+ ``` python
88
+ from starlette.testclient import TestClient
89
+ ```
90
+
91
+ ``` python
92
+ client = TestClient(app)
93
+ r = client.get('/user/Jeremy')
94
+ r
95
+ ```
96
+
97
+ <Response [200 OK]>
98
+
99
+ TestClient uses `httpx` behind the scenes, so it returns a
100
+ `httpx.Response`, which has a `text` attribute with our response body:
101
+
102
+ ``` python
103
+ r.text
104
+ ```
105
+
106
+ 'Good day to you, Jeremy!'
107
+
108
+ FastHTML has special handling of tags created using `fastcore.xml`, so
109
+ you can return web pages without worrying about Jinja, templates, or any
110
+ of that stuff. This also means you can `pip install` styled rich
111
+ component libraries, since it’s all just pure python:
112
+
113
+ ``` python
114
+ @app.get('/html/{idx}')
115
+ async def get_html(idx:int):
116
+ return Body(
117
+ H4("Wow look here"),
118
+ P(f'It looks like you are visitor {idx}! Next is {idx+1}.')
119
+ )
120
+ ```
121
+
122
+ ``` python
123
+ from IPython import display
124
+ ```
125
+
126
+ ``` python
127
+ display.HTML(client.get('/html/1').text)
128
+ ```
129
+
130
+ <body>
131
+ <h4>
132
+ Wow look here
133
+ </h4>
134
+ <p>
135
+ It looks like you are visitor 1! Next is 2.
136
+ </p>
137
+ </body>
@@ -0,0 +1,113 @@
1
+ # fasthtml
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ `fasthtml` is a library for writing fast and scalable Starlette-powered
7
+ web applications, without having to learn much (if any!) Starlette.
8
+ Instead, you just use plain python functions for each page in your app –
9
+ you don’t even need to learn Javascript. The finished app will be about
10
+ as fast as a Python web server can be (which is pretty fast –
11
+ e.g. Instagram runs on Python), and you can create pretty much anything.
12
+ This isn’t one of those stripped-down dashboard making thingies.
13
+
14
+ This is a way to write real web applications, without the fuss.
15
+
16
+ To learn how to use it, please visit the
17
+ [documentation](https://answerdotai.github.io/fasthtml/).
18
+
19
+ ## Install
20
+
21
+ ``` sh
22
+ pip install python-fasthtml
23
+ ```
24
+
25
+ ## How to use
26
+
27
+ Import `fasthtml`, and you’ll probably want the widgets from
28
+ `fastcore.xml` too.
29
+
30
+ ``` python
31
+ from fasthtml import *
32
+ from fastcore.xml import *
33
+ ```
34
+
35
+ Create your app.
36
+
37
+ ``` python
38
+ app = FastHTML()
39
+ ```
40
+
41
+ Create your routes. The syntax is largely the same as the wonderful
42
+ [FastAPI](https://fastapi.tiangolo.com/) (which is what you should be
43
+ using instead of this if you’re creating a JSON service. FastHTML is for
44
+ mainly for making HTML web apps, not APIs).
45
+
46
+ Note that you need to include the types of your parameters, so that
47
+ [`FastHTML`](https://AnswerDotAI.github.io/fasthtml/core.html#fasthtml)
48
+ knows what to pass to your function. Here, we’re just expecting a
49
+ string:
50
+
51
+ ``` python
52
+ @app.get('/user/{nm}')
53
+ def get_nm(nm:str): return f"Good day to you, {nm}!"
54
+ ```
55
+
56
+ Normally you’d save this into a file such as main.py, and then run it in
57
+ `uvicorn` using:
58
+
59
+ uvicorn main:app
60
+
61
+ However, for testing, we can use Starlette’s `TestClient` to try it out:
62
+
63
+ ``` python
64
+ from starlette.testclient import TestClient
65
+ ```
66
+
67
+ ``` python
68
+ client = TestClient(app)
69
+ r = client.get('/user/Jeremy')
70
+ r
71
+ ```
72
+
73
+ <Response [200 OK]>
74
+
75
+ TestClient uses `httpx` behind the scenes, so it returns a
76
+ `httpx.Response`, which has a `text` attribute with our response body:
77
+
78
+ ``` python
79
+ r.text
80
+ ```
81
+
82
+ 'Good day to you, Jeremy!'
83
+
84
+ FastHTML has special handling of tags created using `fastcore.xml`, so
85
+ you can return web pages without worrying about Jinja, templates, or any
86
+ of that stuff. This also means you can `pip install` styled rich
87
+ component libraries, since it’s all just pure python:
88
+
89
+ ``` python
90
+ @app.get('/html/{idx}')
91
+ async def get_html(idx:int):
92
+ return Body(
93
+ H4("Wow look here"),
94
+ P(f'It looks like you are visitor {idx}! Next is {idx+1}.')
95
+ )
96
+ ```
97
+
98
+ ``` python
99
+ from IPython import display
100
+ ```
101
+
102
+ ``` python
103
+ display.HTML(client.get('/html/1').text)
104
+ ```
105
+
106
+ <body>
107
+ <h4>
108
+ Wow look here
109
+ </h4>
110
+ <p>
111
+ It looks like you are visitor 1! Next is 2.
112
+ </p>
113
+ </body>
@@ -0,0 +1,3 @@
1
+ __version__ = "0.0.2"
2
+ from .core import *
3
+
@@ -0,0 +1,23 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/fasthtml',
5
+ 'doc_host': 'https://AnswerDotAI.github.io',
6
+ 'git_url': 'https://github.com/AnswerDotAI/fasthtml',
7
+ 'lib_path': 'fasthtml'},
8
+ 'syms': { 'fasthtml.core': { 'fasthtml.core.FastHTML': ('core.html#fasthtml', 'fasthtml/core.py'),
9
+ 'fasthtml.core.FastHTML.__call__': ('core.html#fasthtml.__call__', 'fasthtml/core.py'),
10
+ 'fasthtml.core.FastHTML.__init__': ('core.html#fasthtml.__init__', 'fasthtml/core.py'),
11
+ 'fasthtml.core.FastHTML.add_route': ('core.html#fasthtml.add_route', 'fasthtml/core.py'),
12
+ 'fasthtml.core.FastHTML.route': ('core.html#fasthtml.route', 'fasthtml/core.py'),
13
+ 'fasthtml.core.RouteX': ('core.html#routex', 'fasthtml/core.py'),
14
+ 'fasthtml.core.RouteX.__init__': ('core.html#routex.__init__', 'fasthtml/core.py'),
15
+ 'fasthtml.core._find_p': ('core.html#_find_p', 'fasthtml/core.py'),
16
+ 'fasthtml.core._fix_anno': ('core.html#_fix_anno', 'fasthtml/core.py'),
17
+ 'fasthtml.core._form_arg': ('core.html#_form_arg', 'fasthtml/core.py'),
18
+ 'fasthtml.core._from_body': ('core.html#_from_body', 'fasthtml/core.py'),
19
+ 'fasthtml.core._wrap_ep': ('core.html#_wrap_ep', 'fasthtml/core.py'),
20
+ 'fasthtml.core._wrap_req': ('core.html#_wrap_req', 'fasthtml/core.py'),
21
+ 'fasthtml.core._wrap_resp': ('core.html#_wrap_resp', 'fasthtml/core.py'),
22
+ 'fasthtml.core.date': ('core.html#date', 'fasthtml/core.py'),
23
+ 'fasthtml.core.snake2hyphens': ('core.html#snake2hyphens', 'fasthtml/core.py')}}}
@@ -0,0 +1,133 @@
1
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../00_core.ipynb.
2
+
3
+ # %% auto 0
4
+ __all__ = ['empty', 'date', 'snake2hyphens', 'RouteX', 'FastHTML']
5
+
6
+ # %% ../00_core.ipynb 2
7
+ import json, dateutil
8
+
9
+ from fastcore.utils import *
10
+ from fastcore.xml import *
11
+
12
+ from types import UnionType
13
+ from typing import Optional, get_type_hints, get_args, get_origin, Union, Mapping
14
+ from datetime import datetime
15
+ from dataclasses import dataclass,fields,is_dataclass,MISSING,asdict
16
+ from inspect import isfunction,ismethod,signature,Parameter
17
+ from functools import wraps, partialmethod
18
+
19
+ from starlette.applications import Starlette
20
+ from starlette.routing import Route, Mount
21
+ from starlette.responses import Response, HTMLResponse, FileResponse, JSONResponse
22
+ from starlette.requests import Request
23
+ from starlette.staticfiles import StaticFiles
24
+ from starlette.exceptions import HTTPException
25
+ from starlette._utils import is_async_callable
26
+
27
+ # %% ../00_core.ipynb 5
28
+ empty = Parameter.empty
29
+
30
+ # %% ../00_core.ipynb 6
31
+ def _wrap_resp(resp, cls):
32
+ if isinstance(resp, Response): return resp
33
+ if cls is not empty: return cls(resp)
34
+ if isinstance(resp, (list,tuple)): return HTMLResponse(to_xml(resp))
35
+ if isinstance(resp, str): cls = HTMLResponse
36
+ elif isinstance(resp, Mapping): cls = JSONResponse
37
+ else:
38
+ resp = str(resp)
39
+ cls = HTMLResponse
40
+ return cls(resp)
41
+
42
+ # %% ../00_core.ipynb 7
43
+ def _fix_anno(t):
44
+ origin = get_origin(t)
45
+ if origin is Union or origin is UnionType:
46
+ t = first(o for o in get_args(t) if o!=type(None))
47
+ if t==bool: return str2bool
48
+ return t
49
+
50
+ # %% ../00_core.ipynb 8
51
+ def date(s): return dateutil.parser.parse(s)
52
+
53
+ # %% ../00_core.ipynb 9
54
+ def _form_arg(fld, body):
55
+ res = body.get(fld.name, None)
56
+ if not res: res = fld.default
57
+ assert res is not MISSING
58
+ anno = _fix_anno(fld.type)
59
+ if res is not None: res = anno(res)
60
+ return res
61
+
62
+ # %% ../00_core.ipynb 10
63
+ async def _from_body(req, arg, p):
64
+ body = await req.form()
65
+ cargs = {o.name:_form_arg(o, body) for o in fields(p.annotation)}
66
+ return p.annotation(**cargs)
67
+
68
+ # %% ../00_core.ipynb 11
69
+ def snake2hyphens(s):
70
+ s = snake2camel(s)
71
+ return camel2words(s, '-')
72
+
73
+ # %% ../00_core.ipynb 12
74
+ async def _find_p(req, arg:str, p):
75
+ if is_dataclass(p.annotation): return await _from_body(req, arg, p)
76
+ res = req.path_params.get(arg, None)
77
+ if not res: res = req.query_params.get(arg, None)
78
+ if not res: res = req.cookies.get(arg, None)
79
+ if not res: res = req.headers.get(snake2hyphens(arg), None)
80
+ if not res: res = p.default
81
+ if res is empty: return None
82
+ anno = _fix_anno(p.annotation)
83
+ if res is not None and anno is not empty: res = anno(res)
84
+ return res
85
+
86
+ # %% ../00_core.ipynb 13
87
+ async def _wrap_req(req, params):
88
+ items = [(k,v) for k,v in params.items()
89
+ if v.annotation is not empty or v.default is not empty]
90
+ if len(params)==1 and not items: return [req]
91
+ return [await _find_p(req, arg, p) for arg,p in items]
92
+
93
+ # %% ../00_core.ipynb 14
94
+ def _wrap_ep(f):
95
+ if not (isfunction(f) or ismethod(f)): return f
96
+ sig = signature(f)
97
+ params = sig.parameters
98
+ cls = sig.return_annotation
99
+
100
+ async def _f(req):
101
+ req = await _wrap_req(req, params)
102
+ resp = f(*req)
103
+ if is_async_callable(f): resp = await resp
104
+ return _wrap_resp(resp, cls)
105
+ return _f
106
+
107
+ # %% ../00_core.ipynb 15
108
+ class RouteX(Route):
109
+ def __init__(self, path, endpoint, *args, **kw):
110
+ ep = _wrap_ep(endpoint)
111
+ super().__init__(path, ep, *args, **kw)
112
+
113
+ # %% ../00_core.ipynb 16
114
+ class FastHTML:
115
+ def __init__(self): self.rd = {}
116
+
117
+ async def __call__(self, scope, recv, send):
118
+ routes = list(self.rd.values())
119
+ app = Starlette(debug=True, routes=routes)
120
+ return await app(scope, recv, send)
121
+
122
+ def add_route(self, route):
123
+ meth = first(route.methods)
124
+ self.rd[(route.path,meth)] = route
125
+
126
+ def route(self, path, meth='GET'):
127
+ def _inner(f):
128
+ self.add_route(RouteX(path, f, methods=[meth]))
129
+ return f
130
+ return _inner
131
+
132
+ for o in 'get post put delete patch head trace options'.split():
133
+ setattr(FastHTML, o, partialmethod(FastHTML.route, meth=o.capitalize()))
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.1
2
+ Name: python-fasthtml
3
+ Version: 0.0.2
4
+ Summary: The fastest way to create an HTML app
5
+ Home-page: https://github.com/AnswerDotAI/fasthtml
6
+ Author: Jeremy Howard
7
+ Author-email: github@jhoward.fastmail.fm
8
+ License: Apache Software License 2.0
9
+ Keywords: nbdev jupyter notebook python
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: fastcore
19
+ Requires-Dist: python-dateutil
20
+ Requires-Dist: starlette
21
+ Provides-Extra: dev
22
+ Requires-Dist: httpx; extra == "dev"
23
+ Requires-Dist: ipython; extra == "dev"
24
+
25
+ # fasthtml
26
+
27
+
28
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
29
+
30
+ `fasthtml` is a library for writing fast and scalable Starlette-powered
31
+ web applications, without having to learn much (if any!) Starlette.
32
+ Instead, you just use plain python functions for each page in your app –
33
+ you don’t even need to learn Javascript. The finished app will be about
34
+ as fast as a Python web server can be (which is pretty fast –
35
+ e.g. Instagram runs on Python), and you can create pretty much anything.
36
+ This isn’t one of those stripped-down dashboard making thingies.
37
+
38
+ This is a way to write real web applications, without the fuss.
39
+
40
+ To learn how to use it, please visit the
41
+ [documentation](https://answerdotai.github.io/fasthtml/).
42
+
43
+ ## Install
44
+
45
+ ``` sh
46
+ pip install python-fasthtml
47
+ ```
48
+
49
+ ## How to use
50
+
51
+ Import `fasthtml`, and you’ll probably want the widgets from
52
+ `fastcore.xml` too.
53
+
54
+ ``` python
55
+ from fasthtml import *
56
+ from fastcore.xml import *
57
+ ```
58
+
59
+ Create your app.
60
+
61
+ ``` python
62
+ app = FastHTML()
63
+ ```
64
+
65
+ Create your routes. The syntax is largely the same as the wonderful
66
+ [FastAPI](https://fastapi.tiangolo.com/) (which is what you should be
67
+ using instead of this if you’re creating a JSON service. FastHTML is for
68
+ mainly for making HTML web apps, not APIs).
69
+
70
+ Note that you need to include the types of your parameters, so that
71
+ [`FastHTML`](https://AnswerDotAI.github.io/fasthtml/core.html#fasthtml)
72
+ knows what to pass to your function. Here, we’re just expecting a
73
+ string:
74
+
75
+ ``` python
76
+ @app.get('/user/{nm}')
77
+ def get_nm(nm:str): return f"Good day to you, {nm}!"
78
+ ```
79
+
80
+ Normally you’d save this into a file such as main.py, and then run it in
81
+ `uvicorn` using:
82
+
83
+ uvicorn main:app
84
+
85
+ However, for testing, we can use Starlette’s `TestClient` to try it out:
86
+
87
+ ``` python
88
+ from starlette.testclient import TestClient
89
+ ```
90
+
91
+ ``` python
92
+ client = TestClient(app)
93
+ r = client.get('/user/Jeremy')
94
+ r
95
+ ```
96
+
97
+ <Response [200 OK]>
98
+
99
+ TestClient uses `httpx` behind the scenes, so it returns a
100
+ `httpx.Response`, which has a `text` attribute with our response body:
101
+
102
+ ``` python
103
+ r.text
104
+ ```
105
+
106
+ 'Good day to you, Jeremy!'
107
+
108
+ FastHTML has special handling of tags created using `fastcore.xml`, so
109
+ you can return web pages without worrying about Jinja, templates, or any
110
+ of that stuff. This also means you can `pip install` styled rich
111
+ component libraries, since it’s all just pure python:
112
+
113
+ ``` python
114
+ @app.get('/html/{idx}')
115
+ async def get_html(idx:int):
116
+ return Body(
117
+ H4("Wow look here"),
118
+ P(f'It looks like you are visitor {idx}! Next is {idx+1}.')
119
+ )
120
+ ```
121
+
122
+ ``` python
123
+ from IPython import display
124
+ ```
125
+
126
+ ``` python
127
+ display.HTML(client.get('/html/1').text)
128
+ ```
129
+
130
+ <body>
131
+ <h4>
132
+ Wow look here
133
+ </h4>
134
+ <p>
135
+ It looks like you are visitor 1! Next is 2.
136
+ </p>
137
+ </body>
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ settings.ini
5
+ setup.py
6
+ fasthtml/__init__.py
7
+ fasthtml/_modidx.py
8
+ fasthtml/core.py
9
+ python_fasthtml.egg-info/PKG-INFO
10
+ python_fasthtml.egg-info/SOURCES.txt
11
+ python_fasthtml.egg-info/dependency_links.txt
12
+ python_fasthtml.egg-info/entry_points.txt
13
+ python_fasthtml.egg-info/not-zip-safe
14
+ python_fasthtml.egg-info/requires.txt
15
+ python_fasthtml.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [nbdev]
2
+ fasthtml = fasthtml._modidx:d
@@ -0,0 +1,7 @@
1
+ fastcore
2
+ python-dateutil
3
+ starlette
4
+
5
+ [dev]
6
+ httpx
7
+ ipython
@@ -0,0 +1,37 @@
1
+ [DEFAULT]
2
+ repo = fasthtml
3
+ lib_name = fasthtml
4
+ version = 0.0.2
5
+ min_python = 3.10
6
+ license = apache2
7
+ requirements = fastcore python-dateutil starlette
8
+ dev_requirements = httpx ipython
9
+ black_formatting = False
10
+ doc_path = _docs
11
+ lib_path = fasthtml
12
+ nbs_path = .
13
+ recursive = True
14
+ tst_flags = notest
15
+ put_version_in_init = True
16
+ branch = main
17
+ custom_sidebar = False
18
+ doc_host = https://AnswerDotAI.github.io
19
+ doc_baseurl = /fasthtml
20
+ git_url = https://github.com/AnswerDotAI/fasthtml
21
+ title = fasthtml
22
+ audience = Developers
23
+ author = Jeremy Howard
24
+ author_email = github@jhoward.fastmail.fm
25
+ copyright = 2024 onwards, Jeremy Howard
26
+ description = The fastest way to create an HTML app
27
+ keywords = nbdev jupyter notebook python
28
+ language = English
29
+ status = 3
30
+ user = AnswerDotAI
31
+ readme_nb = index.ipynb
32
+ allowed_metadata_keys =
33
+ allowed_cell_metadata_keys =
34
+ jupyter_hooks = True
35
+ clean_ids = True
36
+ clear_all = False
37
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,57 @@
1
+ from pkg_resources import parse_version
2
+ from configparser import ConfigParser
3
+ import setuptools, shlex
4
+ assert parse_version(setuptools.__version__)>=parse_version('36.2')
5
+
6
+ # note: all settings are in settings.ini; edit there, not here
7
+ config = ConfigParser(delimiters=['='])
8
+ config.read('settings.ini', encoding='utf-8')
9
+ cfg = config['DEFAULT']
10
+
11
+ cfg_keys = 'version description keywords author author_email'.split()
12
+ expected = cfg_keys + "lib_name user branch license status min_python audience language".split()
13
+ for o in expected: assert o in cfg, "missing expected setting: {}".format(o)
14
+ setup_cfg = {o:cfg[o] for o in cfg_keys}
15
+
16
+ licenses = {
17
+ 'apache2': ('Apache Software License 2.0','OSI Approved :: Apache Software License'),
18
+ 'mit': ('MIT License', 'OSI Approved :: MIT License'),
19
+ 'gpl2': ('GNU General Public License v2', 'OSI Approved :: GNU General Public License v2 (GPLv2)'),
20
+ 'gpl3': ('GNU General Public License v3', 'OSI Approved :: GNU General Public License v3 (GPLv3)'),
21
+ 'bsd3': ('BSD License', 'OSI Approved :: BSD License'),
22
+ }
23
+ statuses = [ '1 - Planning', '2 - Pre-Alpha', '3 - Alpha',
24
+ '4 - Beta', '5 - Production/Stable', '6 - Mature', '7 - Inactive' ]
25
+ py_versions = '3.6 3.7 3.8 3.9 3.10'.split()
26
+
27
+ requirements = shlex.split(cfg.get('requirements', ''))
28
+ if cfg.get('pip_requirements'): requirements += shlex.split(cfg.get('pip_requirements', ''))
29
+ min_python = cfg['min_python']
30
+ lic = licenses.get(cfg['license'].lower(), (cfg['license'], None))
31
+ dev_requirements = (cfg.get('dev_requirements') or '').split()
32
+
33
+ setuptools.setup(
34
+ name = 'python-fasthtml',
35
+ license = lic[0],
36
+ classifiers = [
37
+ 'Development Status :: ' + statuses[int(cfg['status'])],
38
+ 'Intended Audience :: ' + cfg['audience'].title(),
39
+ 'Natural Language :: ' + cfg['language'].title(),
40
+ ] + ['Programming Language :: Python :: '+o for o in py_versions[py_versions.index(min_python):]] + (['License :: ' + lic[1] ] if lic[1] else []),
41
+ url = cfg['git_url'],
42
+ packages = setuptools.find_packages(),
43
+ include_package_data = True,
44
+ install_requires = requirements,
45
+ extras_require={ 'dev': dev_requirements },
46
+ dependency_links = cfg.get('dep_links','').split(),
47
+ python_requires = '>=' + cfg['min_python'],
48
+ long_description = open('README.md', encoding='utf-8').read(),
49
+ long_description_content_type = 'text/markdown',
50
+ zip_safe = False,
51
+ entry_points = {
52
+ 'console_scripts': cfg.get('console_scripts','').split(),
53
+ 'nbdev': [f'{cfg.get("lib_path")}={cfg.get("lib_path")}._modidx:d']
54
+ },
55
+ **setup_cfg)
56
+
57
+