| 1 |
from datasette import hookimpl |
| 2 |
from datasette.utils.asgi import Response |
| 3 |
from functools import wraps |
| 4 |
import markupsafe |
| 5 |
import json |
| 6 |
|
| 7 |
|
| 8 |
@hookimpl |
| 9 |
def extra_js_urls(): |
| 10 |
return [ |
| 11 |
{ |
| 12 |
"url": "https://plugin-example.datasette.io/jquery.js", |
| 13 |
"sri": "SRIHASH", |
| 14 |
}, |
| 15 |
"https://plugin-example.datasette.io/plugin2.js", |
| 16 |
] |
| 17 |
|
| 18 |
|
| 19 |
@hookimpl |
| 20 |
def render_cell(value, database): |
| 21 |
# Render {"href": "...", "label": "..."} as link |
| 22 |
if not isinstance(value, str): |
| 23 |
return None |
| 24 |
stripped = value.strip() |
| 25 |
if not stripped.startswith("{") and stripped.endswith("}"): |
| 26 |
return None |
| 27 |
try: |
| 28 |
data = json.loads(value) |
| 29 |
except ValueError: |
| 30 |
return None |
| 31 |
if not isinstance(data, dict): |
| 32 |
return None |
| 33 |
if set(data.keys()) != {"href", "label"}: |
| 34 |
return None |
| 35 |
href = data["href"] |
| 36 |
if not ( |
| 37 |
href.startswith("/") |
| 38 |
or href.startswith("http://") |
| 39 |
or href.startswith("https://") |
| 40 |
): |
| 41 |
return None |
| 42 |
return markupsafe.Markup( |
| 43 |
'<a data-database="{database}" href="{href}">{label}</a>'.format( |
| 44 |
database=database, |
| 45 |
href=markupsafe.escape(data["href"]), |
| 46 |
label=markupsafe.escape(data["label"] or "") or " ", |
| 47 |
) |
| 48 |
) |
| 49 |
|
| 50 |
|
| 51 |
@hookimpl |
| 52 |
def extra_template_vars(template, database, table, view_name, request, datasette): |
| 53 |
# This helps unit tests that want to run assertions against the request object: |
| 54 |
datasette._last_request = request |
| 55 |
|
| 56 |
async def query_database(sql): |
| 57 |
first_db = list(datasette.databases.keys())[0] |
| 58 |
return (await datasette.execute(first_db, sql)).rows[0][0] |
| 59 |
|
| 60 |
async def inner(): |
| 61 |
return { |
| 62 |
"extra_template_vars_from_awaitable": json.dumps( |
| 63 |
{ |
| 64 |
"template": template, |
| 65 |
"scope_path": request.scope["path"] if request else None, |
| 66 |
"awaitable": True, |
| 67 |
}, |
| 68 |
default=lambda b: b.decode("utf8"), |
| 69 |
), |
| 70 |
"query_database": query_database, |
| 71 |
} |
| 72 |
|
| 73 |
return inner |
| 74 |
|
| 75 |
|
| 76 |
@hookimpl |
| 77 |
def asgi_wrapper(datasette): |
| 78 |
def wrap_with_databases_header(app): |
| 79 |
@wraps(app) |
| 80 |
async def add_x_databases_header(scope, receive, send): |
| 81 |
async def wrapped_send(event): |
| 82 |
if event["type"] == "http.response.start": |
| 83 |
original_headers = event.get("headers") or [] |
| 84 |
event = { |
| 85 |
"type": event["type"], |
| 86 |
"status": event["status"], |
| 87 |
"headers": original_headers |
| 88 |
+ [ |
| 89 |
[ |
| 90 |
b"x-databases", |
| 91 |
", ".join(datasette.databases.keys()).encode("utf-8"), |
| 92 |
] |
| 93 |
], |
| 94 |
} |
| 95 |
await send(event) |
| 96 |
|
| 97 |
await app(scope, receive, wrapped_send) |
| 98 |
|
| 99 |
return add_x_databases_header |
| 100 |
|
| 101 |
return wrap_with_databases_header |
| 102 |
|
| 103 |
|
| 104 |
@hookimpl |
| 105 |
def actor_from_request(datasette, request): |
| 106 |
async def inner(): |
| 107 |
if request.args.get("_bot2"): |
| 108 |
result = await datasette.get_database().execute("select 1 + 1") |
| 109 |
return {"id": "bot2", "1+1": result.first()[0]} |
| 110 |
else: |
| 111 |
return None |
| 112 |
|
| 113 |
return inner |
| 114 |
|
| 115 |
|
| 116 |
@hookimpl |
| 117 |
def permission_allowed(datasette, actor, action): |
| 118 |
# Testing asyncio version of permission_allowed |
| 119 |
async def inner(): |
| 120 |
assert 2 == (await datasette.get_database().execute("select 1 + 1")).first()[0] |
| 121 |
if action == "this_is_allowed_async": |
| 122 |
return True |
| 123 |
elif action == "this_is_denied_async": |
| 124 |
return False |
| 125 |
|
| 126 |
return inner |
| 127 |
|
| 128 |
|
| 129 |
@hookimpl |
| 130 |
def prepare_jinja2_environment(env, datasette): |
| 131 |
env.filters["format_numeric"] = lambda s: f"{float(s):,.0f}" |
| 132 |
env.filters["to_hello"] = lambda s: datasette._HELLO |
| 133 |
|
| 134 |
|
| 135 |
@hookimpl |
| 136 |
def startup(datasette): |
| 137 |
async def inner(): |
| 138 |
result = await datasette.get_database().execute("select 1 + 1") |
| 139 |
datasette._startup_hook_calculation = result.first()[0] |
| 140 |
|
| 141 |
return inner |
| 142 |
|
| 143 |
|
| 144 |
@hookimpl |
| 145 |
def canned_queries(datasette, database): |
| 146 |
async def inner(): |
| 147 |
return { |
| 148 |
"from_async_hook": "select {}".format( |
| 149 |
( |
| 150 |
await datasette.get_database(database).execute("select 1 + 1") |
| 151 |
).first()[0] |
| 152 |
) |
| 153 |
} |
| 154 |
|
| 155 |
return inner |
| 156 |
|
| 157 |
|
| 158 |
@hookimpl(trylast=True) |
| 159 |
def menu_links(datasette, actor): |
| 160 |
async def inner(): |
| 161 |
if actor: |
| 162 |
return [{"href": datasette.urls.instance(), "label": "Hello 2"}] |
| 163 |
|
| 164 |
return inner |
| 165 |
|
| 166 |
|
| 167 |
@hookimpl |
| 168 |
def table_actions(datasette, database, table, actor, request): |
| 169 |
async def inner(): |
| 170 |
if actor: |
| 171 |
label = "From async" |
| 172 |
if request.args.get("_hello"): |
| 173 |
label += " " + request.args["_hello"] |
| 174 |
return [{"href": datasette.urls.instance(), "label": label}] |
| 175 |
|
| 176 |
return inner |
| 177 |
|
| 178 |
|
| 179 |
@hookimpl |
| 180 |
def register_routes(datasette): |
| 181 |
config = datasette.plugin_config("register-route-demo") |
| 182 |
if not config: |
| 183 |
return |
| 184 |
path = config["path"] |
| 185 |
|
| 186 |
def new_table(request): |
| 187 |
return Response.text("/db/table: {}".format(sorted(request.url_vars.items()))) |
| 188 |
|
| 189 |
return [ |
| 190 |
(r"/{}/$".format(path), lambda: Response.text(path.upper())), |
| 191 |
# Also serves to demonstrate over-ride of default paths: |
| 192 |
(r"/(?P<db_name>[^/]+)/(?P<table_and_format>[^/]+?$)", new_table), |
| 193 |
] |
| 194 |
|
| 195 |
|
| 196 |
@hookimpl |
| 197 |
def handle_exception(datasette, request, exception): |
| 198 |
datasette._exception_hook_fired = (request, exception) |
| 199 |
if request.args.get("_custom_error"): |
| 200 |
return Response.text("_custom_error") |
| 201 |
elif request.args.get("_custom_error_async"): |
| 202 |
|
| 203 |
async def inner(): |
| 204 |
return Response.text("_custom_error_async") |
| 205 |
|
| 206 |
return inner |
| 207 |
|
| 208 |
|
| 209 |
@hookimpl(specname="register_routes") |
| 210 |
def register_triger_error(): |
| 211 |
return ((r"/trigger-error", lambda: 1 / 0),) |