csrftoken() now works with .render_template(), closes #863

pull/866/head
Simon Willison 2020-06-23 20:23:30 -07:00
rodzic eed116ac05
commit 28bb1c5189
4 zmienionych plików z 19 dodań i 1 usunięć

Wyświetl plik

@ -739,6 +739,7 @@ class Datasette:
"extra_css_urls": self._asset_urls("extra_css_urls", template, context),
"extra_js_urls": self._asset_urls("extra_js_urls", template, context),
"base_url": self.config("base_url"),
"csrftoken": request.scope["csrftoken"] if request else lambda: "",
},
**extra_template_vars,
}

Wyświetl plik

@ -103,7 +103,6 @@ class BaseView(AsgiView):
**context,
**{
"database_url": self.database_url,
"csrftoken": request.scope["csrftoken"],
"database_color": self.database_color,
"show_messages": lambda: self.ds._show_messages(request),
"select_templates": [

Wyświetl plik

@ -182,11 +182,17 @@ def register_routes():
else:
return Response.json(await request.post_vars())
async def csrftoken_form(request, datasette):
return Response.html(
await datasette.render_template("csrftoken_form.html", request=request)
)
return [
(r"/one/$", one),
(r"/two/(?P<name>.*)$", two),
(r"/three/$", three),
(r"/post/$", post),
(r"/csrftoken-form/$", csrftoken_form),
]

Wyświetl plik

@ -580,6 +580,18 @@ def test_register_routes_post(app_client):
assert "post data" == response.json["this is"]
def test_register_routes_csrftoken(tmpdir):
templates = tmpdir / "templates"
templates.mkdir()
(templates / "csrftoken_form.html").write_text(
"CSRFTOKEN: {{ csrftoken() }}", "utf-8"
)
with make_app_client(template_dir=templates) as client:
response = client.get("/csrftoken-form/")
expected_token = client.ds._last_request.scope["csrftoken"]()
assert "CSRFTOKEN: {}".format(expected_token) == response.text
def test_register_routes_asgi(app_client):
response = app_client.get("/three/")
assert {"hello": "world"} == response.json