Skip to content

Instantly share code, notes, and snippets.

@andrewsosa
Created November 10, 2017 17:20
Show Gist options
  • Save andrewsosa/2f3d1f5543afe90fb773b33f8d981662 to your computer and use it in GitHub Desktop.
Save andrewsosa/2f3d1f5543afe90fb773b33f8d981662 to your computer and use it in GitHub Desktop.
[ApiMultiView Proposal] A view which tasks out work() calls to delegate ApiView classes
#
# hackfsu_com.views.generic.api_multi_view
#
class ApiMultiView(ApiView):
http_method_names = [] # This must be overridden for every multiview
http_delegates = {} # Dictionary of delegate ApiView objects, key is the method
def work(self, request: HttpRequest, req: dict, res: dict):
delegate = self.http_delegates.get(request.method, None)
if delegate is None:
raise InternalServerError(ValidationError('Not a valid method for route.', params=[request.path, request.method]))
# Call the delegate ApiView's work function
delegate.work(request, req, res)
#
# api/views/example/__init__.py
#
class MultiViewExample(ApiMultiView):
http_method_names = ['get', 'post']
http_delegates = {
'get': MultiViewExampleGet,
'post': MultiViewExamplePost
}
#
# api/views/example/get.py
#
class MultiViewExampleGet(ApiView):
def work(self, request: HttpRequest, req: dict, res: dict):
"""
Do something here for GET requests
"""
super().work(request, req, res)
#
# api/views/example/post.py
#
class MultiViewExamplePost(ApiView):
def work(self, request: HttpRequest, req: dict, res: dict):
"""
Do something here for POST requests
"""
super().work(request, req, res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment