| 1 |
import asyncio |
| 2 |
from datasette import hookimpl |
| 3 |
from datasette.facets import Facet |
| 4 |
from datasette import tracer |
| 5 |
from datasette.utils import path_with_added_args |
| 6 |
from datasette.utils.asgi import asgi_send_json, Response |
| 7 |
import base64 |
| •8 |
import pint |
| 9 |
import json |
| 10 |
|
| 11 |
ureg = pint.UnitRegistry() |
| 12 |
|
| 13 |
|
| 14 |
@hookimpl |
| 15 |
def prepare_connection(conn, database, datasette): |
| 16 |
def convert_units(amount, from_, to_): |
| 17 |
"""select convert_units(100, 'm', 'ft');""" |
| 18 |
return (amount * ureg(from_)).to(to_).to_tuple()[0] |
| 19 |
|
| 20 |
conn.create_function("convert_units", 3, convert_units) |
| 21 |
|
| 22 |
def prepare_connection_args(): |
| 23 |
return 'database={}, datasette.plugin_config("name-of-plugin")={}'.format( |
| 24 |
database, datasette.plugin_config("name-of-plugin") |
| 25 |
) |
| 26 |
|
| 27 |
conn.create_function("prepare_connection_args", 0, prepare_connection_args) |
| 28 |
|
| 29 |
|
| 30 |
@hookimpl |
| 31 |
def extra_css_urls(template, database, table, view_name, columns, request, datasette): |
| 32 |
async def inner(): |
| 33 |
return [ |
| 34 |
"https://plugin-example.datasette.io/{}/extra-css-urls-demo.css".format( |
| 35 |
base64.b64encode( |
| 36 |
json.dumps( |
| 37 |
{ |
| 38 |
"template": template, |
| 39 |
"database": database, |
| 40 |
"table": table, |
| 41 |
"view_name": view_name, |
| 42 |
"request_path": ( |
| 43 |
request.path if request is not None else None |
| 44 |
), |
| 45 |
"added": ( |
| 46 |
await datasette.get_database().execute("select 3 * 5") |
| 47 |
).first()[0], |
| 48 |
"columns": columns, |
| 49 |
} |
| 50 |
).encode("utf8") |
| 51 |
).decode("utf8") |
| 52 |
) |
| 53 |
] |
| 54 |
|
| 55 |
return inner |
| 56 |
|
| 57 |
|
| 58 |
@hookimpl |
| 59 |
def extra_js_urls(): |
| 60 |
return [ |
| 61 |
{ |
| 62 |
"url": "https://plugin-example.datasette.io/jquery.js", |
| 63 |
"sri": "SRIHASH", |
| 64 |
}, |
| 65 |
"https://plugin-example.datasette.io/plugin1.js", |
| 66 |
{"url": "https://plugin-example.datasette.io/plugin.module.js", "module": True}, |
| 67 |
] |
| 68 |
|
| 69 |
|
| 70 |
@hookimpl |
| 71 |
def extra_body_script( |
| 72 |
template, database, table, view_name, columns, request, datasette |
| 73 |
): |
| 74 |
async def inner(): |
| 75 |
script = "var extra_body_script = {};".format( |
| 76 |
json.dumps( |
| 77 |
{ |
| 78 |
"template": template, |
| 79 |
"database": database, |
| 80 |
"table": table, |
| 81 |
"config": datasette.plugin_config( |
| 82 |
"name-of-plugin", |
| 83 |
database=database, |
| 84 |
table=table, |
| 85 |
), |
| 86 |
"view_name": view_name, |
| 87 |
"request_path": request.path if request is not None else None, |
| 88 |
"added": ( |
| 89 |
await datasette.get_database().execute("select 3 * 5") |
| 90 |
).first()[0], |
| 91 |
"columns": columns, |
| 92 |
} |
| 93 |
) |
| 94 |
) |
| 95 |
return {"script": script, "module": True} |
| 96 |
|
| 97 |
return inner |
| 98 |
|
| 99 |
|
| 100 |
@hookimpl |
| 101 |
def render_cell(row, value, column, table, database, datasette): |
| 102 |
async def inner(): |
| 103 |
# Render some debug output in cell with value RENDER_CELL_DEMO |
| 104 |
if value == "RENDER_CELL_DEMO": |
| 105 |
return json.dumps( |
| 106 |
{ |
| 107 |
"row": dict(row), |
| 108 |
"column": column, |
| 109 |
"table": table, |
| 110 |
"database": database, |
| 111 |
"config": datasette.plugin_config( |
| 112 |
"name-of-plugin", |
| 113 |
database=database, |
| 114 |
table=table, |
| 115 |
), |
| 116 |
} |
| 117 |
) |
| 118 |
elif value == "RENDER_CELL_ASYNC": |
| 119 |
return ( |
| 120 |
await datasette.get_database(database).execute( |
| 121 |
"select 'RENDER_CELL_ASYNC_RESULT'" |
| 122 |
) |
| 123 |
).single_value() |
| 124 |
|
| 125 |
return inner |
| 126 |
|
| 127 |
|
| 128 |
@hookimpl |
| 129 |
def extra_template_vars( |
| 130 |
template, database, table, view_name, columns, request, datasette |
| 131 |
): |
| 132 |
return { |
| 133 |
"extra_template_vars": json.dumps( |
| 134 |
{ |
| 135 |
"template": template, |
| 136 |
"scope_path": request.scope["path"] if request else None, |
| 137 |
"columns": columns, |
| 138 |
}, |
| 139 |
default=lambda b: b.decode("utf8"), |
| 140 |
) |
| 141 |
} |
| 142 |
|
| 143 |
|
| 144 |
@hookimpl |
| 145 |
def prepare_jinja2_environment(env, datasette): |
| 146 |
async def select_times_three(s): |
| 147 |
db = datasette.get_database() |
| 148 |
return (await db.execute("select 3 * ?", [int(s)])).first()[0] |
| 149 |
|
| 150 |
async def inner(): |
| 151 |
env.filters["select_times_three"] = select_times_three |
| 152 |
|
| 153 |
return inner |
| 154 |
|
| 155 |
|
| 156 |
@hookimpl |
| 157 |
def register_facet_classes(): |
| 158 |
return [DummyFacet] |
| 159 |
|
| 160 |
|
| 161 |
class DummyFacet(Facet): |
| 162 |
type = "dummy" |
| 163 |
|
| 164 |
async def suggest(self): |
| 165 |
columns = await self.get_columns(self.sql, self.params) |
| 166 |
return ( |
| 167 |
[ |
| 168 |
{ |
| 169 |
"name": column, |
| 170 |
"toggle_url": self.ds.absolute_url( |
| 171 |
self.request, |
| 172 |
path_with_added_args(self.request, {"_facet_dummy": column}), |
| 173 |
), |
| 174 |
"type": "dummy", |
| 175 |
} |
| 176 |
for column in columns |
| 177 |
] |
| 178 |
if self.request.args.get("_dummy_facet") |
| 179 |
else [] |
| 180 |
) |
| 181 |
|
| 182 |
async def facet_results(self): |
| 183 |
facet_results = {} |
| 184 |
facets_timed_out = [] |
| 185 |
return facet_results, facets_timed_out |
| 186 |
|
| 187 |
|
| 188 |
@hookimpl |
| 189 |
def actor_from_request(datasette, request): |
| 190 |
if request.args.get("_bot"): |
| 191 |
return {"id": "bot"} |
| 192 |
else: |
| 193 |
return None |
| 194 |
|
| 195 |
|
| 196 |
@hookimpl |
| 197 |
def asgi_wrapper(): |
| 198 |
def wrap(app): |
| 199 |
async def maybe_set_actor_in_scope(scope, receive, send): |
| 200 |
if b"_actor_in_scope" in scope.get("query_string", b""): |
| 201 |
scope = dict(scope, actor={"id": "from-scope"}) |
| 202 |
print(scope) |
| 203 |
await app(scope, receive, send) |
| 204 |
|
| 205 |
return maybe_set_actor_in_scope |
| 206 |
|
| 207 |
return wrap |
| 208 |
|
| 209 |
|
| 210 |
@hookimpl |
| 211 |
def permission_allowed(actor, action): |
| 212 |
if action == "this_is_allowed": |
| 213 |
return True |
| 214 |
elif action == "this_is_denied": |
| 215 |
return False |
| 216 |
elif action == "view-database-download": |
| 217 |
return actor.get("can_download") if actor else None |
| 218 |
|
| 219 |
|
| 220 |
@hookimpl |
| 221 |
def register_routes(): |
| 222 |
async def one(datasette): |
| 223 |
return Response.text( |
| 224 |
(await datasette.get_database().execute("select 1 + 1")).first()[0] |
| 225 |
) |
| 226 |
|
| 227 |
async def two(request): |
| 228 |
name = request.url_vars["name"] |
| 229 |
greeting = request.args.get("greeting") |
| 230 |
return Response.text(f"{greeting} {name}") |
| 231 |
|
| 232 |
async def three(scope, send): |
| 233 |
await asgi_send_json( |
| 234 |
send, {"hello": "world"}, status=200, headers={"x-three": "1"} |
| 235 |
) |
| 236 |
|
| 237 |
async def post(request): |
| 238 |
if request.method == "GET": |
| 239 |
return Response.html(request.scope["csrftoken"]()) |
| 240 |
else: |
| 241 |
return Response.json(await request.post_vars()) |
| 242 |
|
| 243 |
async def csrftoken_form(request, datasette): |
| 244 |
return Response.html( |
| 245 |
await datasette.render_template("csrftoken_form.html", request=request) |
| 246 |
) |
| 247 |
|
| 248 |
def not_async(): |
| 249 |
return Response.html("This was not async") |
| 250 |
|
| 251 |
def add_message(datasette, request): |
| 252 |
datasette.add_message(request, "Hello from messages") |
| 253 |
return Response.html("Added message") |
| 254 |
|
| 255 |
async def render_message(datasette, request): |
| 256 |
return Response.html( |
| 257 |
await datasette.render_template("render_message.html", request=request) |
| 258 |
) |
| 259 |
|
| 260 |
def login_as_root(datasette, request): |
| 261 |
# Mainly for the latest.datasette.io demo |
| 262 |
if request.method == "POST": |
| 263 |
response = Response.redirect("/") |
| 264 |
response.set_cookie( |
| 265 |
"ds_actor", datasette.sign({"a": {"id": "root"}}, "actor") |
| 266 |
) |
| 267 |
return response |
| 268 |
return Response.html( |
| 269 |
""" |
| 270 |
<form action="{}" method="POST"> |
| 271 |
<p> |
| 272 |
<input type="hidden" name="csrftoken" value="{}"> |
| 273 |
<input type="submit" value="Sign in as root user"></p> |
| 274 |
</form> |
| 275 |
""".format( |
| 276 |
request.path, request.scope["csrftoken"]() |
| 277 |
) |
| 278 |
) |
| 279 |
|
| 280 |
def asgi_scope(scope): |
| 281 |
return Response.json(scope, default=repr) |
| 282 |
|
| 283 |
async def parallel_queries(datasette): |
| 284 |
db = datasette.get_database() |
| 285 |
with tracer.trace_child_tasks(): |
| 286 |
one, two = await asyncio.gather( |
| 287 |
db.execute("select coalesce(sleep(0.1), 1)"), |
| 288 |
db.execute("select coalesce(sleep(0.1), 2)"), |
| 289 |
) |
| 290 |
return Response.json({"one": one.single_value(), "two": two.single_value()}) |
| 291 |
|
| 292 |
return [ |
| 293 |
(r"/one/$", one), |
| 294 |
(r"/two/(?P<name>.*)$", two), |
| 295 |
(r"/three/$", three), |
| 296 |
(r"/post/$", post), |
| 297 |
(r"/csrftoken-form/$", csrftoken_form), |
| 298 |
(r"/login-as-root$", login_as_root), |
| 299 |
(r"/not-async/$", not_async), |
| 300 |
(r"/add-message/$", add_message), |
| 301 |
(r"/render-message/$", render_message), |
| 302 |
(r"/asgi-scope$", asgi_scope), |
| 303 |
(r"/parallel-queries$", parallel_queries), |
| 304 |
] |
| 305 |
|
| 306 |
|
| 307 |
@hookimpl |
| 308 |
def startup(datasette): |
| 309 |
datasette._startup_hook_fired = True |
| 310 |
|
| 311 |
# And test some import shortcuts too |
| 312 |
from datasette import Response |
| 313 |
from datasette import Forbidden |
| 314 |
from datasette import NotFound |
| 315 |
from datasette import hookimpl |
| 316 |
from datasette import actor_matches_allow |
| 317 |
|
| 318 |
_ = (Response, Forbidden, NotFound, hookimpl, actor_matches_allow) |
| 319 |
|
| 320 |
|
| 321 |
@hookimpl |
| 322 |
def canned_queries(datasette, database, actor): |
| 323 |
return {"from_hook": f"select 1, '{actor['id'] if actor else 'null'}' as actor_id"} |
| 324 |
|
| 325 |
|
| 326 |
@hookimpl |
| 327 |
def register_magic_parameters(): |
| 328 |
from uuid import uuid4 |
| 329 |
|
| 330 |
def uuid(key, request): |
| 331 |
if key == "new": |
| 332 |
return str(uuid4()) |
| 333 |
else: |
| 334 |
raise KeyError |
| 335 |
|
| 336 |
def request(key, request): |
| 337 |
if key == "http_version": |
| 338 |
return request.scope["http_version"] |
| 339 |
else: |
| 340 |
raise KeyError |
| 341 |
|
| 342 |
return [ |
| 343 |
("request", request), |
| 344 |
("uuid", uuid), |
| 345 |
] |
| 346 |
|
| 347 |
|
| 348 |
@hookimpl |
| 349 |
def forbidden(datasette, request, message): |
| 350 |
datasette._last_forbidden_message = message |
| 351 |
if request.path == "/data2": |
| 352 |
return Response.redirect("/login?message=" + message) |
| 353 |
|
| 354 |
|
| 355 |
@hookimpl |
| 356 |
def menu_links(datasette, actor, request): |
| 357 |
if actor: |
| 358 |
label = "Hello" |
| 359 |
if request.args.get("_hello"): |
| 360 |
label += ", " + request.args["_hello"] |
| 361 |
return [{"href": datasette.urls.instance(), "label": label}] |
| 362 |
|
| 363 |
|
| 364 |
@hookimpl |
| 365 |
def table_actions(datasette, database, table, actor): |
| 366 |
if actor: |
| 367 |
return [ |
| 368 |
{ |
| 369 |
"href": datasette.urls.instance(), |
| 370 |
"label": f"Database: {database}", |
| 371 |
}, |
| 372 |
{"href": datasette.urls.instance(), "label": f"Table: {table}"}, |
| 373 |
] |
| 374 |
|
| 375 |
|
| 376 |
@hookimpl |
| 377 |
def database_actions(datasette, database, actor, request): |
| 378 |
if actor: |
| 379 |
label = f"Database: {database}" |
| 380 |
if request.args.get("_hello"): |
| 381 |
label += " - " + request.args["_hello"] |
| 382 |
return [ |
| 383 |
{ |
| 384 |
"href": datasette.urls.instance(), |
| 385 |
"label": label, |
| 386 |
} |
| 387 |
] |
| 388 |
|
| 389 |
|
| 390 |
@hookimpl |
| 391 |
def skip_csrf(scope): |
| 392 |
return scope["path"] == "/skip-csrf" |