]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
:sparkles: Allow callables (as functools.partial) in path operations (#977)
authorSebastián Ramírez <tiangolo@gmail.com>
Wed, 12 Feb 2020 20:36:14 +0000 (21:36 +0100)
committerGitHub <noreply@github.com>
Wed, 12 Feb 2020 20:36:14 +0000 (21:36 +0100)
fastapi/routing.py
tests/test_callable_endpoint.py [new file with mode: 0644]

index 09c4bf366e017d9d1f5e49e0d4eeec87a1b730b9..bbc2b4133599c7f8fd84a327c78c04f0a8e95c10 100644 (file)
@@ -335,9 +335,7 @@ class APIRoute(routing.Route):
         self.include_in_schema = include_in_schema
         self.response_class = response_class
 
-        assert inspect.isfunction(endpoint) or inspect.ismethod(
-            endpoint
-        ), f"An endpoint must be a function or method"
+        assert callable(endpoint), f"An endpoint must be a callable"
         self.dependant = get_dependant(path=self.path_format, call=self.endpoint)
         for depends in self.dependencies[::-1]:
             self.dependant.dependencies.insert(
diff --git a/tests/test_callable_endpoint.py b/tests/test_callable_endpoint.py
new file mode 100644 (file)
index 0000000..bcc60a0
--- /dev/null
@@ -0,0 +1,24 @@
+from functools import partial
+
+from fastapi import FastAPI
+from starlette.testclient import TestClient
+
+
+def main(some_arg, q: str = None):
+    return {"some_arg": some_arg, "q": q}
+
+
+endpoint = partial(main, "foo")
+
+app = FastAPI()
+
+app.get("/")(endpoint)
+
+
+client = TestClient(app)
+
+
+def test_partial():
+    response = client.get("/?q=bar")
+    data = response.json()
+    assert data == {"some_arg": "foo", "q": "bar"}