Debian Codegraph @

aiohttp_jinja2/helpers.py

raw symbols SCIP
1 """
2 useful context functions, see
3 http://jinja.pocoo.org/docs/dev/api/#jinja2.contextfunction
4 """
5 import warnings
6 from typing import Dict, Optional, TypedDict, Union
7
8 import jinja2
9 from aiohttp import web
10 from yarl import URL
11
12
13 class _Context(TypedDict, total=False):
14 app: web.Application
15
16
17 static_root_key = web.AppKey("static_root_key", str)
18
19
20 @jinja2.pass_context
21 def url_for(
22 context: _Context,
23 __route_name: str,
24 query_: Optional[Dict[str, str]] = None,
25 **parts: Union[str, int]
26 ) -> URL:
27 """Filter for generating urls.
28
29 Usage: {{ url('the-view-name') }} might become "/path/to/view" or
30 {{ url('item-details', id=123, query_={'active': 'true'}) }}
31 might become "/items/1?active=true".
32 """
33 app = context["app"]
34
35 parts_clean: Dict[str, str] = {}
36 for key in parts:
37 val = parts[key]
38 if isinstance(val, str):
39 # if type is inherited from str expilict cast to str makes sense
40 # if type is exactly str the operation is very fast
41 val = str(val)
42 elif type(val) is int:
43 # int inherited classes like bool are forbidden
44 val = str(val)
45 else:
46 raise TypeError(
47 "argument value should be str or int, "
48 "got {} -> [{}] {!r}".format(key, type(val), val)
49 )
50 parts_clean[key] = val
51
52 url = app.router[__route_name].url_for(**parts_clean)
53 if query_:
54 url = url.with_query(query_)
55 return url
56
57
58 @jinja2.pass_context
59 def static_url(context: _Context, static_file_path: str) -> str:
60 """Filter for generating urls for static files.
61
62 NOTE: you'll need to set app[aiohttp_jinja2.static_root_key] to be used as the
63 root for the urls returned.
64
65 Usage: {{ static('styles.css') }} might become
66 "/static/styles.css" or "http://mycdn.example.com/styles.css"
67 """
68 app = context["app"]
69 try:
70 static_url = app[static_root_key]
71 except KeyError:
72 try:
73 # TODO (aiohttp 3.10+): Remove this fallback
74 static_url = app["static_root_url"]
75 except KeyError:
76 raise RuntimeError(
77 "app does not define a static root url, you need to set the url root "
78 "with app[aiohttp_jinja2.static_root_key] = '<static root>'."
79 ) from None
80 else:
81 warnings.warn(
82 "'static_root_url' is deprecated, use aiohttp_jinja2.static_root_key.",
83 category=DeprecationWarning,
84 stacklevel=2,
85 )
86 return "{}/{}".format(static_url.rstrip("/"), static_file_path.lstrip("/"))
87
88
89 GLOBAL_HELPERS = dict(
90 url=url_for,
91 static=static_url,
92 )