question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Endpoint class decorators

See original GitHub issue

I need to implement a decorator for an endpoint, and for some technical reasons, I would like to implement it with a class. I also would like my decorator to not need parenthesis when called. (i.e. prefer @my_decorator over @my_decorator()).

Here is a simple implementation:

from starlette.responses import JSONResponse
from starlette.applications import Starlette
from starlette.routing import Route


class foobar:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)


@foobar
def my_endpoint(request):
    return JSONResponse({"response": "my_endpoint"})


app = Starlette(
    debug=True,
    routes=[
        Route('/my_endpoint', my_endpoint),
    ],
)

But accessing to /my_endpoint produces this traceback:

Traceback (most recent call last):
  File "~/myproject/env/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "~/myproject/env/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "~/myproject/env/lib/python3.8/site-packages/starlette/applications.py", line 102, in __call__
    await self.middleware_stack(scope, receive, send)
  File "~/myproject/env/lib/python3.8/site-packages/starlette/middleware/errors.py", line 178, in __call__
    raise exc from None
  File "~/myproject/env/lib/python3.8/site-packages/starlette/middleware/errors.py", line 156, in __call__
    await self.app(scope, receive, _send)
  File "~/myproject/env/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "~/myproject/env/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "~/myproject/env/lib/python3.8/site-packages/starlette/routing.py", line 551, in __call__
    await route.handle(scope, receive, send)
  File "~/myproject/env/lib/python3.8/site-packages/starlette/routing.py", line 228, in handle
    await self.app(scope, receive, send)
  File "./app.py", line 11, in __call__
    return self.func(*args, **kwargs)
TypeError: my_endpoint() takes 1 positional argument but 3 were given

I am not really sure what is going wrong here. I also did not find documentation about endpoint decorators with starlette. Do I make mistakes when defining my decorator or is it something not supported by starlette?

PS: I used starlette 0.13 and python 3.8

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:2
  • Comments:18 (10 by maintainers)

github_iconTop GitHub Comments

1reaction
Davmuzcommented, Aug 5, 2022

It’s still relevant to me, I used a nasty workaround in several projects.

1reaction
tomchristiecommented, Dec 23, 2019

AFAIU the purpose of the ASGI part of Route() is to support HTTPEndpoint and others — i.e. class-based views, which do implement ASGI.

Right. And actually thinking about it, we don’t need to be doing that.

The request/response function to Route needs to accept a request and return a response. I’d assumed we can do that on CBV’s because eg init just returns the class instance. (So eg in Django there’s a ViewClass.as_view() hoop that users jump through.)

My solution had been “okay, let’s have Route accept either a request/response function, or an ASGI app. Then CBVs can be implemented as mini ASGI apps)

Happily, in our case I think instantiating the CBV can be the request/response function, because “response” here just means, an ASGI callable. So… if the CBV init method accepts a request, and if call implements the ASGI interface and handles dispatch, then the classes are request/response callables.

We can then drop the “Route can also be an ASGI app” case, because we don’t really need it. Mount is appropriate for pointing at apps, Route is appropriate for pointing as req/response callables.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Custom endpoint decorator | Ts.ED - A Node.js and TypeScript ...
Custom endpoint decorator could be interesting when you want to handle a request and perform actions before or after the endpoint method.
Read more >
Decorators | Cloud Endpoints Frameworks for App Engine
The Cloud Endpoints Frameworks for Python decorators describe API configuration, methods, parameters, and other vital details that define the properties and ...
Read more >
View Decorators — Flask Documentation (1.1.x)
Because each view in Flask is a function, decorators can be used to inject additional functionality to one or more functions. The route()...
Read more >
How to add a custom decorator to a FastAPI route?
I want to add that decorator to some endpoints, not every. So custom APIRoute class (Im actually using it) doesnt help. And I...
Read more >
Benchmarking API Endpoints With TypeScript Decorators
You can think of decorators as a function that gets attached to something — usually a class, method, or a property — and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found