├── .gitignore ├── .pre-commit-config.yaml ├── LICENSE ├── README.md ├── docs ├── cli.md ├── htmx.md ├── index.md └── routes.md ├── mkdocs.yml ├── pyproject.toml ├── src └── darkstar │ ├── __init__.py │ ├── __main__.py │ ├── applications.py │ └── templating.py └── test_ast.py /.gitignore: -------------------------------------------------------------------------------- 1 | .venv 2 | *.pyc 3 | __pycache__ 4 | site/ 5 | app.py 6 | dist/ 7 | routes/ 8 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | exclude: | 4 | (?x)( 5 | copier| 6 | .vim 7 | ) 8 | repos: 9 | - repo: https://github.com/pre-commit/pre-commit-hooks 10 | rev: v3.2.0 11 | hooks: 12 | - id: trailing-whitespace 13 | - id: end-of-file-fixer 14 | - id: check-yaml 15 | - id: check-added-large-files 16 | - id: check-merge-conflict 17 | - repo: https://github.com/pre-commit/pygrep-hooks 18 | rev: v1.9.0 # Use the ref you want to point at 19 | hooks: 20 | - id: python-use-type-annotations 21 | - id: python-check-blanket-noqa 22 | - id: python-no-eval 23 | - id: python-no-log-warn 24 | - repo: https://github.com/psf/black 25 | rev: 21.7b0 26 | hooks: 27 | - id: black 28 | - repo: https://github.com/PyCQA/flake8 29 | rev: 3.9.2 30 | hooks: 31 | - id: flake8 32 | args: ["--ignore=E1,W"] 33 | - repo: https://github.com/sqlalchemyorg/zimports/ 34 | rev: v0.4.0 35 | hooks: 36 | - id: zimports 37 | 38 | - repo: https://github.com/ikamensh/flynt 39 | rev: '0.63' 40 | hooks: 41 | - id: flynt 42 | args: ["--verbose"] 43 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. 30 | 31 | Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 32 | 33 | 3. Grant of Patent License. 34 | 35 | Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 36 | 37 | 4. Redistribution. 38 | 39 | You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 40 | 41 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 42 | You must cause any modified files to carry prominent notices stating that You changed the files; and 43 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 44 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 45 | 46 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 47 | 48 | 5. Submission of Contributions. 49 | 50 | Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 51 | 52 | 6. Trademarks. 53 | 54 | This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 55 | 56 | 7. Disclaimer of Warranty. 57 | 58 | Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 59 | 60 | 8. Limitation of Liability. 61 | 62 | In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 63 | 64 | 9. Accepting Warranty or Additional Liability. 65 | 66 | While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 67 | 68 | END OF TERMS AND CONDITIONS 69 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dark Star 2 | 3 | Dark Star is a web framework that provides filesystem routing for 4 | [Starlette](https://starlette.io) and first-class support for server-side rendering. 5 | 6 | Dark Star routes are defined by their filesystem path and both the route's 7 | backend code and template are contained in the first page. 8 | 9 | ## Motivation 10 | 11 | Dark Star aims to provide an easy way to create web applications using the 12 | [HATEOAS](https://htmx.org/essays/hateoas/) and 13 | [HDA](https://htmx.org/essays/hypermedia-driven-applications/) philosophies 14 | favoured by [htmx](https://htmx.org). It also aims to reduce the boilerplate 15 | code normally needed when creating web apps. In particular, it looks to reduce 16 | the need of having a separate files for view functions and templates. It tries 17 | to embrace [Locality of Behaviour](https://htmx.org/essays/locality-of-behaviour/) 18 | by putting the view function code and template in the same file, and having the 19 | file's path be the route used by Starlette to access the code. 20 | 21 | ## Installation 22 | 23 | ``` 24 | pip install darkstar 25 | ``` 26 | 27 | You can then run the included CLI with: 28 | 29 | ``` 30 | python -m darkstar create-app --help 31 | ``` 32 | 33 | To run your new app, you'll need an ASGI server installed, such a Hypercorn, Daphne, or Uvicorn. 34 | 35 | To run with Uvicorn, first install it: 36 | 37 | ``` 38 | python -m pip install uvicorn[standard] 39 | ``` 40 | 41 | The run your app: 42 | 43 | ``` 44 | python -m uvicorn app:app 45 | ``` 46 | 47 | (This assumes your defined your app as the `app` variable in an `app.py` file.) 48 | -------------------------------------------------------------------------------- /docs/cli.md: -------------------------------------------------------------------------------- 1 | # Dark Star CLI 2 | 3 | Dark Star comes with a CLI that helps you perform basic tasks. 4 | 5 | Run it using the command `darkstar`. 6 | 7 | ```sh 8 | $ darkstar 9 | Usage: cli [OPTIONS] COMMAND [ARGS]... 10 | 11 | Dark Star - a web framework based on Starlette 12 | 13 | Options: 14 | --help Show this message and exit. 15 | 16 | Commands: 17 | create-app 18 | new-route 19 | ``` 20 | 21 | ## `create-app` 22 | 23 | `create-app` takes a directory where a new app and directory structure will be 24 | created. 25 | 26 | ```sh 27 | $ darkstar create-app --help 28 | Usage: cli create-app [OPTIONS] DIRECTORY 29 | 30 | Options: 31 | --htmx / --no-htmx Include htmx script in index.py 32 | --help Show this message and exit. 33 | ``` 34 | 35 | The `--htmx` option will include `script` tags for htmx and hyperscript in the 36 | default `index.py` file. 37 | 38 | ## `new-route` 39 | 40 | `new-route` takes a route path and creates the python file in the correct 41 | location. It will also parse any path parameters and add code to extract them 42 | from the request. 43 | -------------------------------------------------------------------------------- /docs/htmx.md: -------------------------------------------------------------------------------- 1 | # Working with htmx 2 | 3 | Dark Star includes functionality to make working with 4 | [htmx](https://htmx.org) easier. In particular, it includes a piece of 5 | middleware to allow access to the `request.state.htmx` variable, which can be 6 | used in functions and templates to test whether a request came from htmx. 7 | 8 | ## Example Template File 9 | 10 | In the following example, the template will only extend `index.py` if the 11 | request is not from htmx. 12 | 13 | profile = request.path_params.get("profile") 14 | 15 | """ 16 | {% if request.state.htmx %}{% extends 'index.py' %}{% endif %} 17 | Hello {{profile}} - here are your account details 18 | 19 | ... 20 | """ 21 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # Dark Star 2 | 3 | Dark Star is a simple web framework built on top of Starlette that prioritises 4 | server-side rendering with templates. 5 | 6 | The vast majority of functionality is delegated to Starlette - Dark Star helps 7 | you organise your code and keeps your code next to your templates. 8 | 9 | ## Installation 10 | 11 | Install with `pip`: 12 | 13 | ``` 14 | pip install darkstar 15 | ``` 16 | 17 | Create a new app: 18 | 19 | ``` 20 | python -m darkstar create-app 21 | # or 22 | darkstar create-app 23 | ``` 24 | 25 | 26 | ## Starter Application 27 | 28 | Dark Star uses default values for its directories, so getting started is very 29 | easy. If you didn't use the CLI's `create-app` command then create an `app.py` 30 | file with the following content: 31 | 32 | ```python 33 | from darkstar.applications import DarkStar 34 | 35 | app = DarkStar() 36 | ``` 37 | 38 | The above code will assume your routes are in the `routes` directory and static 39 | files are in the `static` directory. 40 | 41 | You can then run your application using an ASGI server, such as uvircorn: 42 | 43 | ```python 44 | pip install uvicorn[standard] # if not already installed 45 | uvicorn app:app 46 | ``` 47 | 48 | 49 | ## Example Project layout 50 | 51 | ```python 52 | my_app.py # The main application file 53 | static/ # Static files under /static/ 54 | routes/ 55 | index.py # The root template - inherited by other templates 56 | users.py # A template file that maps to the /users/ url 57 | users/ 58 | {profile}.py # A template that maps to the /user/{profile}/ url 59 | # and lets the code access the value of `profile` 60 | ``` 61 | ## Example Template File 62 | 63 | Template files are regular python files which contain the template at the end as a triple-quoted string. 64 | 65 | ```python 66 | profile = request.path_params.get("profile") 67 | 68 | """ 69 | {% extends 'index.py' %} 70 | Hello {{profile}} - here are your account details 71 | 72 | ... other content 73 | 74 | """ 75 | ``` 76 | 77 | All templates get passed the `request` parameter as per Starlette's normal 78 | routes. The template is then included as a triple-quoted string at the end of 79 | the file. All variables defined in the code will be available in the template 80 | for use when rendering. 81 | 82 | Another example: 83 | 84 | users = Users.objects.all() 85 | 86 | """ 87 | {% extends 'index.py' %} 88 |
Use the new-route
command to create your first route
See the docs for more information.
30 | {% endblock %} 31 | {% endraw -%} 32 | 33 | 34 | """ 35 | ''' 36 | 37 | TEMPLATE_TEMPLATE = '''\ 38 | {{param_text}} 39 | """ 40 | {% raw %} 41 | {% extends 'index.py' %} 42 | {% block content %} 43 | {% endblock %} 44 | {% endraw %} 45 | """ 46 | ''' 47 | 48 | 49 | @click.group("cli") 50 | @click.pass_context 51 | def cli(ctx): 52 | """Dark Star - a web framework based on Starlette""" 53 | pass 54 | 55 | 56 | @cli.command("create-app") 57 | @click.argument("directory", type=click.Path()) 58 | @click.option("--htmx/--no-htmx", help="Include htmx script in index.py", default=False) 59 | def create_app(directory, htmx): 60 | path = Path(directory) 61 | 62 | routes_dir = path / "routes" 63 | print(f"Creating {routes_dir}") 64 | routes_dir.mkdir(exist_ok=True, parents=True) 65 | 66 | static_dir = path / "static" 67 | print(f"Creating {static_dir}") 68 | static_dir.mkdir(exist_ok=True, parents=True) 69 | 70 | index_path = path / "routes" / "index.py" 71 | if not index_path.exists(): 72 | print(f"Creating {index_path}") 73 | index_path.write_text(Template(INDEX_TEMPLATE).render(htmx=htmx)) 74 | app_file = path / "app.py" 75 | if not app_file.exists(): 76 | print(f"Creating {app_file}") 77 | app_file.write_text(Template(APP_TEMPLATE).render()) 78 | 79 | 80 | @cli.command("new-route") 81 | @click.argument("path", type=click.Path()) 82 | def new_route(path): 83 | 84 | route_path = Path("routes") / path.lstrip("/").rstrip("/") 85 | route_path = route_path.with_suffix(".py") 86 | if not route_path.exists(): 87 | print(f"Adding new route {route_path}") 88 | route_path.parent.mkdir(parents=True, exist_ok=True) 89 | *_, params = compile_path(str(route_path)) 90 | param_text = "\n".join( 91 | f'{key} = request.path_params["{key}"]' for key in params.keys() 92 | ).strip() 93 | route_path.write_text(Template(TEMPLATE_TEMPLATE).render(param_text=param_text)) 94 | 95 | 96 | def main(): 97 | cli(prog_name="cli") 98 | 99 | 100 | if __name__ == "__main__": 101 | main() 102 | -------------------------------------------------------------------------------- /src/darkstar/applications.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from hashlib import md5 3 | from io import BytesIO 4 | from pathlib import Path 5 | import shlex 6 | from tokenize import COMMENT 7 | from tokenize import tokenize 8 | import typing 9 | 10 | from starlette.applications import Starlette 11 | from starlette.middleware import Middleware 12 | from starlette.requests import Request 13 | from starlette.responses import Response 14 | from starlette.routing import BaseRoute 15 | from starlette.routing import Mount 16 | from starlette.routing import Route 17 | from starlette.staticfiles import StaticFiles 18 | 19 | from .templating import Jinja2Templates 20 | 21 | 22 | dark_star_templates = None 23 | 24 | 25 | class FunctionAdder(ast.NodeTransformer): 26 | """Makes our bare files into functions""" 27 | 28 | def __init__(self, template_path, function_name, *args, **kwargs): 29 | super().__init__(*args, **kwargs) 30 | self.function_name = function_name 31 | self.template_path = template_path 32 | self.new_return = ast.parse( 33 | f"""return dark_star_templates.TemplateResponse("{self.template_path}", locals())""" 34 | ) 35 | 36 | def visit_Module(self, node): 37 | super().generic_visit(node) 38 | 39 | wrapper = ast.AsyncFunctionDef( 40 | name=self.function_name, 41 | decorator_list=[], 42 | args=ast.arguments( 43 | posonlyargs=[], 44 | kwonlyargs=[], 45 | defaults=[], 46 | kw_defaults=[], 47 | args=[ast.arg(arg="request")], 48 | ), 49 | ) 50 | wrapper.body = node.body 51 | wrapper.body.extend(self.new_return.body) 52 | node.body = [wrapper] 53 | return node 54 | 55 | 56 | def get_options(code): 57 | tokens = tokenize(BytesIO(code.strip().encode("utf-8")).readline) 58 | for toknum, tokval, (srow, scol), *_ in tokens: 59 | if srow > 1: 60 | return {} 61 | if toknum == COMMENT: 62 | _, *options = shlex.split(tokval) 63 | break 64 | route_options = {} 65 | if options: 66 | for option in options: 67 | key, _, value = option.partition("=") 68 | if key == "methods": 69 | route_options[key] = [x.strip() for x in value.split(",")] 70 | elif key == "name": 71 | route_options[key] = value 72 | return route_options 73 | 74 | 75 | class DarkStar(Starlette): 76 | def __init__( 77 | self, 78 | routes_path: typing.Union[str, Path] = "routes", 79 | debug: bool = False, 80 | routes: typing.Sequence[BaseRoute] = [], 81 | static_directory: str = "static", 82 | middleware: typing.Sequence[Middleware] = None, 83 | exception_handlers: typing.Mapping[ 84 | typing.Any, 85 | typing.Callable[ 86 | [Request, Exception], typing.Union[Response, typing.Awaitable[Response]] 87 | ], 88 | ] = None, 89 | on_startup: typing.Sequence[typing.Callable] = None, 90 | on_shutdown: typing.Sequence[typing.Callable] = None, 91 | lifespan: typing.Callable[["Starlette"], typing.AsyncContextManager] = None, 92 | ) -> None: 93 | 94 | global dark_star_templates 95 | dark_star_templates = Jinja2Templates(routes_path) 96 | 97 | self.template_env = dark_star_templates.env 98 | 99 | path_routes = self._collect_routes(routes_path) 100 | 101 | if not any( 102 | type(route) == Mount and type(route.app) == StaticFiles for route in routes 103 | ): 104 | routes.append(Mount("/static/", StaticFiles(directory=static_directory))) 105 | 106 | super().__init__( 107 | debug, 108 | path_routes + routes, 109 | middleware, 110 | exception_handlers, 111 | on_startup, 112 | on_shutdown, 113 | ) 114 | 115 | def _collect_routes(self, routes_path) -> typing.Sequence[BaseRoute]: 116 | routes = [] 117 | 118 | for path in Path(routes_path).rglob("*.py"): 119 | if path.is_file(): 120 | python = path.read_text() 121 | function_name = f"ds_{md5(str(path).encode()).hexdigest()}" 122 | 123 | modded_function = ast.fix_missing_locations( 124 | FunctionAdder(path.relative_to(routes_path), function_name).visit( 125 | ast.parse(python) 126 | ) 127 | ) 128 | 129 | exec(compile(modded_function, f"{path}", "exec"), globals()) 130 | 131 | route_options = get_options(python) 132 | 133 | if path.relative_to(routes_path) == Path("index.py"): 134 | if "name" not in route_options: 135 | route_options["name"] = "index" 136 | routes.append(Route("/", globals()[function_name], **route_options)) 137 | else: 138 | routes.append( 139 | Route( 140 | f"/{path.relative_to(routes_path).with_suffix('')}/", 141 | globals()[function_name], 142 | **route_options, 143 | ) 144 | ) 145 | 146 | return routes 147 | -------------------------------------------------------------------------------- /src/darkstar/templating.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import os 3 | from os import PathLike 4 | from pathlib import Path 5 | import typing 6 | 7 | import jinja2 8 | from jinja2.environment import Environment 9 | from jinja2.exceptions import TemplateNotFound 10 | from jinja2.loaders import FileSystemLoader as JinjaFileSystemLoader 11 | from jinja2.loaders import split_template_path 12 | from jinja2.utils import open_if_exists 13 | from starlette.templating import Jinja2Templates as StarletteJinja2Templates 14 | 15 | # @contextfunction renamed to @pass_context in Jinja 3.0, to be removed in 3.1 16 | if hasattr(jinja2, "pass_context"): 17 | pass_context = jinja2.pass_context 18 | else: # pragma: nocover 19 | pass_context = jinja2.contextfunction 20 | 21 | 22 | class TemplateExtractor(ast.NodeVisitor): 23 | """Makes our bare files into functions""" 24 | 25 | def visit_Constant(self, node): 26 | super().generic_visit(node) 27 | 28 | self.value = node.value 29 | 30 | 31 | class FileSystemLoader(JinjaFileSystemLoader): 32 | def get_source( 33 | self, environment: Environment, template: str 34 | ) -> typing.Tuple[str, str, typing.Callable[[], bool]]: 35 | 36 | pieces = split_template_path(template) 37 | 38 | for searchpath in self.searchpath: 39 | filename = os.path.join(searchpath, *pieces) 40 | 41 | f = open_if_exists(filename) 42 | 43 | if f is None: 44 | continue 45 | try: 46 | contents = f.read().decode(self.encoding) 47 | finally: 48 | f.close() 49 | 50 | if Path(filename).suffix == ".py": 51 | extractor = TemplateExtractor() 52 | extractor.visit(ast.parse(contents)) 53 | contents = extractor.value 54 | 55 | mtime = os.path.getmtime(filename) 56 | 57 | def uptodate() -> bool: 58 | try: 59 | return os.path.getmtime(filename) == mtime 60 | except OSError: 61 | return False 62 | 63 | return contents, filename, uptodate 64 | raise TemplateNotFound(template) 65 | 66 | 67 | class Jinja2Templates(StarletteJinja2Templates): 68 | def _create_env( 69 | self, directory: typing.Union[str, PathLike], **env_options: typing.Any 70 | ) -> "jinja2.Environment": 71 | @pass_context 72 | def url_for(context: dict, name: str, **path_params: typing.Any) -> str: 73 | request = context["request"] 74 | return request.url_for(name, **path_params) 75 | 76 | loader = FileSystemLoader(directory) 77 | env_options.setdefault("loader", loader) 78 | env_options.setdefault("autoescape", True) 79 | 80 | env = jinja2.Environment(**env_options) 81 | env.globals["url_for"] = url_for 82 | return env 83 | -------------------------------------------------------------------------------- /test_ast.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from io import BytesIO 3 | from shlex import split 4 | from tokenize import COMMENT 5 | from tokenize import tokenize 6 | 7 | from astpretty import pprint 8 | 9 | code1 = """ 10 | print(2) 11 | print(2) 12 | """ 13 | code2 = """ 14 | async def f(request): 15 | print(2) 16 | """ 17 | 18 | 19 | class NumberChanger(ast.NodeTransformer): 20 | """Changes all number literals to 42.""" 21 | 22 | def visit_Module(self, node): 23 | super().generic_visit(node) 24 | 25 | if isinstance(node, ast.Module): 26 | wrapper = ast.AsyncFunctionDef( 27 | name="do_request", 28 | decorator_list=[], 29 | args=ast.arguments( 30 | posonlyargs=[], 31 | kwonlyargs=[], 32 | defaults=[], 33 | kw_defaults=[], 34 | args=[ast.arg(arg="request")], 35 | ), 36 | ) 37 | wrapper.body = node.body 38 | node.body = [wrapper] 39 | return node 40 | if not isinstance(node, ast.Constant) or not isinstance(node.value, int): 41 | return node 42 | 43 | return ast.Constant(value=42) 44 | 45 | 46 | # pprint(ast.parse(code1)) 47 | # pprint(ast.parse(code2)) 48 | # pprint(a) 49 | modded1 = ast.fix_missing_locations(NumberChanger().visit(ast.parse(code1))) 50 | # pprint(modded1) 51 | modded2 = ast.parse(code2) 52 | # pprint(modded2) 53 | # print(modded1 == modded2) 54 | # print("--------------") 55 | # print(ast.unparse(modded1)) 56 | # print(ast.unparse(modded2)) 57 | 58 | # pprint( 59 | # ast.parse( 60 | # """ 61 | # return dark_star_templates.TemplateResponse("{template_path}", locals()) 62 | # """ 63 | # ) 64 | # ) 65 | # code = ''' 66 | # print('') 67 | # """adfa 68 | # fadf 69 | # a 70 | # fadf 71 | # ad 72 | # """ 73 | # ''' 74 | # pprint(ast.parse(code)) 75 | 76 | code = """ 77 | 78 | 79 | # methods="GET, POST" name="this is my name" 80 | 81 | 82 | r = request 83 | """ 84 | g = tokenize(BytesIO(code.strip().encode("utf-8")).readline) 85 | 86 | 87 | for toknum, tokval, (srow, scol), *_ in g: 88 | if toknum == COMMENT: 89 | print(tokval, srow) 90 | for s in split(tokval): 91 | print(s) 92 | 93 | pprint(ast.parse(code)) 94 | --------------------------------------------------------------------------------