Skip to content

Instantly share code, notes, and snippets.

@mick88
Last active June 21, 2021 09:21
Show Gist options
  • Save mick88/a29f3dd675c2c7a4ea6e549b707189a6 to your computer and use it in GitHub Desktop.
Save mick88/a29f3dd675c2c7a4ea6e549b707189a6 to your computer and use it in GitHub Desktop.
Django: Lazy view
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
@mick88
Copy link
Author

mick88 commented Jun 21, 2021

To use in urls.py, just instantiate `LazyView` with class path argument and use as a normal view:
url(r'^/view$', LazyView('path.to.ViewClass').as_view(), name="url-name"),   

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment