From eb8545c172b4b12e89dcc08a976f037d881346c4 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Fri, 15 Mar 2024 15:29:03 -0700 Subject: [PATCH] Refactor duplicate code in DatasetteClient, closes #2307 --- datasette/app.py | 43 +++++++++++-------------------------------- 1 file changed, 11 insertions(+), 32 deletions(-) diff --git a/datasette/app.py b/datasette/app.py index f1b057af..aa75d772 100644 --- a/datasette/app.py +++ b/datasette/app.py @@ -1933,54 +1933,33 @@ class DatasetteClient: path = f"http://localhost{path}" return path - async def get(self, path, **kwargs): + async def _request(self, method, path, **kwargs): async with httpx.AsyncClient( transport=httpx.ASGITransport(app=self.app), cookies=kwargs.pop("cookies", None), ) as client: - return await client.get(self._fix(path), **kwargs) + return await getattr(client, method)(self._fix(path), **kwargs) + + async def get(self, path, **kwargs): + return await self._request("get", path, **kwargs) async def options(self, path, **kwargs): - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=self.app), - cookies=kwargs.pop("cookies", None), - ) as client: - return await client.options(self._fix(path), **kwargs) + return await self._request("options", path, **kwargs) async def head(self, path, **kwargs): - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=self.app), - cookies=kwargs.pop("cookies", None), - ) as client: - return await client.head(self._fix(path), **kwargs) + return await self._request("head", path, **kwargs) async def post(self, path, **kwargs): - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=self.app), - cookies=kwargs.pop("cookies", None), - ) as client: - return await client.post(self._fix(path), **kwargs) + return await self._request("post", path, **kwargs) async def put(self, path, **kwargs): - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=self.app), - cookies=kwargs.pop("cookies", None), - ) as client: - return await client.put(self._fix(path), **kwargs) + return await self._request("put", path, **kwargs) async def patch(self, path, **kwargs): - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=self.app), - cookies=kwargs.pop("cookies", None), - ) as client: - return await client.patch(self._fix(path), **kwargs) + return await self._request("patch", path, **kwargs) async def delete(self, path, **kwargs): - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=self.app), - cookies=kwargs.pop("cookies", None), - ) as client: - return await client.delete(self._fix(path), **kwargs) + return await self._request("delete", path, **kwargs) async def request(self, method, path, **kwargs): avoid_path_rewrites = kwargs.pop("avoid_path_rewrites", None)