Last active
June 21, 2021 09:21
-
-
Save mick88/a29f3dd675c2c7a4ea6e549b707189a6 to your computer and use it in GitHub Desktop.
Django: Lazy view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Callable | |
from django.utils.module_loading import import_string | |
from django.views import View | |
class LazyView: | |
""" | |
Wrapper for view class that can be used for urls to avoid loading the view class at the import time. | |
The view is imported at first access and cached. | |
To use in urls.py, just instantiate `LazyView` with class path argument and use as a normal view: | |
```python | |
url(r'^/view$', LazyView('path.to.ViewClass').as_view(), name="url-name"), | |
``` | |
""" | |
def __init__(self, view_cls_path: str) -> None: | |
super().__init__() | |
self.view_cls_path = view_cls_path | |
def view_func(self, *args, **kwargs): | |
if not hasattr(self, 'view'): | |
view_cls: type[View] = import_string(self.view_cls_path) | |
self.view: Callable = view_cls.as_view(**self.initkwargs) | |
return self.view(*args, **kwargs) | |
def as_view(self, **initkwargs): | |
self.initkwargs = initkwargs | |
return self.view_func |
Author
mick88
commented
Jun 21, 2021
•
To use in urls.py, just instantiate `LazyView` with class path argument and use as a normal view:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment