define routing to a class method? #382
-
define routing to a class method? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
@erhuabushuo by "class method" you mean a method defined into a class decorated by The first is not supported, but the second one. |
Beta Was this translation helpful? Give feedback.
-
So I understand it would be like that:
Jose |
Beta Was this translation helpful? Give feedback.
-
like flask class based view |
Beta Was this translation helpful? Give feedback.
-
@erhuabushuo Emmett doesn't provide any ready-to-go facilities for that, mainly because in Emmett a class based view is an anti-pattern, secondly to prevent wasting performance in creating objects during request flow. You might want to implement your own from emmett import AppModule
class ViewModule(AppModule):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._define_routes()
def _define_routes(self):
for method in ["get", "post", "put", "delete"]:
if handler := getattr(self, method, None):
self.route(methods=[method], name=method)(handler)
class TodoView(ViewModule):
def get(self):
return {"key": "value"}
todo = app.module(__name__, "todo", url_prefix="/todo", module_class=TodoView) Mind that the instance is shared across all requests, so avoid to set attributes to |
Beta Was this translation helpful? Give feedback.
@erhuabushuo Emmett doesn't provide any ready-to-go facilities for that, mainly because in Emmett a class based view is an anti-pattern, secondly to prevent wasting performance in creating objects during request flow.
You might want to implement your own
AppModule
class for such logic, somewhat like the REST extension does: