Ejemplo n.º 1
0
 def test_cache_page(self):
     def my_view(request):
         return "response"
     my_view_cached = cache_page(123)(my_view)
     self.assertEqual(my_view_cached(HttpRequest()), "response")
     my_view_cached2 = cache_page(123, key_prefix="test")(my_view)
     self.assertEqual(my_view_cached2(HttpRequest()), "response")
Ejemplo n.º 2
0
 def test_cache_page_new_style(self):
     """
     Test that we can call cache_page the new way
     """
     def my_view(request):
         return "response"
     my_view_cached = cache_page(123)(my_view)
     self.assertEqual(my_view_cached(HttpRequest()), "response")
     my_view_cached2 = cache_page(123, key_prefix="test")(my_view)
     self.assertEqual(my_view_cached2(HttpRequest()), "response")
Ejemplo n.º 3
0
 def get_urls(self):
     urlpatterns = super(ShippingApplication, self).get_urls()
     urlpatterns += patterns('',
         url(r'^city-lookup/(?P<slug>[\w-]+)/$', cache_page(60*10)(self.city_lookup_view.as_view()),
             name='city-lookup'),
     )
     urlpatterns += patterns('',
         url(r'^details/(?P<slug>[\w-]+)/$', cache_page(60*10)(self.shipping_details_view.as_view()),
             name='charge-details'),
     )
     return self.post_process_urls(urlpatterns)
Ejemplo n.º 4
0
def cache_page(cls=None, **cache_kwargs):
    """
    Apply the ``cache_page`` decorator to all the handlers in a class-based
    view that delegate to the ``dispatch`` method.

    Optional arguments
    ``timeout`` -- Cache timeout, in seconds.``

    Usage (without timeout parameter):
      @cache_page
      class MyView (TemplateView):
        ...

    Usage (with 5 minute timeout):
      @cache_page(60*5)
      class MyView(TemplateView):
        ...

    Based on login required decorator: http://djangosnippets.org/snippets/2495/
    """

    if cls is not None:
        # Check that the View class is a class-based view. This can either be
        # done by checking inheritance from django.views.generic.View, or by
        # checking that the ViewClass has a ``dispatch`` method.
        if not hasattr(cls, 'dispatch'):
            raise TypeError(('View class is not valid: %r.  Class-based views '
                             'must have a dispatch method.') % cls)

        timeout = None
        if cache_kwargs.has_key('timeout'):
            timeout = cache_kwargs.pop('timeout')
        original = cls.dispatch
        if timeout:
            modified = method_decorator(cache_page(timeout, **cache_kwargs))(original)
        else:
            modified = method_decorator(cache_page(**cache_kwargs))(original)
        cls.dispatch = modified

        return cls

    else:
        # If ViewClass is None, then this was applied as a decorator with
        # parameters. An inner decorator will be used to capture the ViewClass,
        # and return the actual decorator method.
        def inner_decorator(inner_cls):
            return cache_page(inner_cls, **cache_kwargs)

        return inner_decorator
Ejemplo n.º 5
0
 def test_cache_page_old_style(self):
     """
     Test that we can call cache_page the old way
     """
     def my_view(request):
         return "response"
     with warnings.catch_warnings(record=True):
         my_view_cached = cache_page(my_view, 123)
         self.assertEqual(my_view_cached(HttpRequest()), "response")
         my_view_cached2 = cache_page(my_view, 123, key_prefix="test")
         self.assertEqual(my_view_cached2(HttpRequest()), "response")
         my_view_cached3 = cache_page(my_view)
         self.assertEqual(my_view_cached3(HttpRequest()), "response")
         my_view_cached4 = cache_page()(my_view)
         self.assertEqual(my_view_cached4(HttpRequest()), "response")
Ejemplo n.º 6
0
 def _(request, *args, **kwargs):
     # Anonymous might be a better user_key, but is a valid username
     user_key = '~~~~' if not request.user.is_authenticated \
         else request.user.username
     return cache_page(
         timeout, key_prefix="user:%s" % user_key
     )(view_func)(request, *args, **kwargs)
Ejemplo n.º 7
0
 def wrapper(request, library=None):
   cache_ttl = get_cache_ttl(library)
   if cache_ttl is not None:
     cached_load_view = cache_page(cache_ttl)(load_view)
     return cached_load_view(request, library)
   else:
     return load_view(request, library)
Ejemplo n.º 8
0
 def dispatch(self, *args, **kwargs):
     if hasattr(self.request, 'user') and self.request.user.is_authenticated:
         # Logged-in, return the page without caching.
         return super().dispatch(*args, **kwargs)
     else:
         # Unauthenticated user; use caching.
         return cache_page(self.get_cache_timeout())(super().dispatch)(*args, **kwargs)
Ejemplo n.º 9
0
 def decorator(request, *args, **kwargs):
     # Build the custom cache key prefix
     timeout = 60 * settings.MINUTES_TO_CACHE
     key_prefix = cache_page_prefix(request)
     # Return cache_page function normally called by @cache_page decorator
     # with our custom cache key prefix.
     return cache_page(timeout, key_prefix=key_prefix)(view)(request, *args,
                                                             **kwargs)
Ejemplo n.º 10
0
def no_cache(view):
    """Decorator that disables any cache for view

    Instead of setting headers and other boring stuff, use django decorator
    with 0 cache timeout
    """
    wrapper = cache_page(0)
    return wrapper(view)
Ejemplo n.º 11
0
 def _wrapped_view(request, *args, **kwargs):
     user = request.user
     if user.is_authenticated() and user.profile.count_notifications():
         return view_func(request, *args, **kwargs)
     else:
         return cache_page(timeout,
             key_prefix="_auth_%s_" % request.user.is_authenticated())(
                 view_func)(request, *args, **kwargs)
Ejemplo n.º 12
0
 def dispatch(self, request, *args, **kwargs):
     cache_timeout = self.get_cache_timeout()
     self.current_site = self.get_current_site(request)
     super_dispatch = super(RuleList, self).dispatch
     if not cache_timeout:
         return super_dispatch(request, *args, **kwargs)
     key_prefix = self.current_site.domain
     cache_decorator = cache_page(cache_timeout, key_prefix=key_prefix)
     return cache_decorator(super_dispatch)(request, *args, **kwargs)
Ejemplo n.º 13
0
def slug_index(request, slug, language):
    locations = models.Location.objects.filter(slug=slug)

    if not locations:
        return redirect("/")

    location = locations[0]

    return cache_page(CACHE_LENGTH)(index)(request, location.id, language)
Ejemplo n.º 14
0
    def configure_urls(self, cls, urls):

        from django.conf.urls import url, patterns
        from cms.views import details
        from django.views.decorators.cache import cache_page
        from cratis.app.i18n.utils import localize_url as _

        if cls.DEBUG:
            urls += patterns('',
                             url(_(r'^$'), details, {'slug': ''}, name='pages-root'),
                             url(_(r'^(?P<slug>[0-9A-Za-z-_.//]+)$'), details, name='pages-details-by-slug'),
            )
        else:
            urls += patterns('',
                             url(_(r'^$'), cache_page(60 * 24)(details), {'slug': ''}, name='pages-root'),
                             url(_(r'^(?P<slug>[0-9A-Za-z-_.//]+)$'), cache_page(60 * 24)(details),
                                 name='pages-details-by-slug'),
            )
Ejemplo n.º 15
0
 def wrapped_view_func(request, *args, **kwargs):
     try:
         (cache_timeout, cache_kwargs) = req_cache_func(request,
                                                        *args,
                                                        **kwargs)
         ret = cache_page(cache_timeout, **cache_kwargs)(view_func)
     except TypeError:
         ret = never_cache(view_func)
     return ret(request, *args, **kwargs)
Ejemplo n.º 16
0
    def get_urls(self):

        if IDM_SUPPORT_ENABLED:
            from wirecloud.fiware.views import oauth_discovery
            return (
                url('^.well-known/oauth$', cache_page(7 * 24 * 60 * 60, key_prefix='well-known-oauth-%s' % get_version_hash())(oauth_discovery), name='oauth.discovery'),
            )
        else:
            return ()
Ejemplo n.º 17
0
 def dispatch(self, *args, **kwargs):
     timeout = self.get_cache_timeout()
     if timeout is None:
         return super(CacheMixin, self).dispatch(*args, **kwargs)
     if isinstance(timeout, (list, tuple)):
         timeout = randint(*timeout)
     response = cache_page(timeout, cache=self.get_cache(), key_prefix=self.get_key_prefix()
                           )(super(CacheMixin, self).dispatch)(*args, **kwargs)
     patch_response_headers(response, timeout)
     return response
Ejemplo n.º 18
0
        def _wrapped_view(request, *args, **kwargs):

            #Don't cache pages that have unique messages
            messages = get_messages(request)
            if len(messages) > 0 or test_func(request.user):

                return view_func(request, *args, **kwargs)

            else:
                return cache_page(cache_duration)(view_func)(request, *args, **kwargs) 
Ejemplo n.º 19
0
 def _wrapped_view(request, *args, **kwargs):
     print('in wrapped view')
     if condition(group, *args, **kwargs):
         key_prefix = get_group_key(compute_group_label(
             group, *args, **kwargs))
         res = cache_page(TIME_TO_CACHE, key_prefix=key_prefix)(
             view_func)(request, *args, **kwargs)
         print('cache\n' + unicode(cache.get(key_prefix)))
         return res
     else:
         return view_func(request, *args, **kwargs)
Ejemplo n.º 20
0
def cache_view(cls=None, **cache_kwargs):
    if cls is not None:
        timeout = cache_kwargs.pop('timeout', None)
        original = cls.dispatch
        args = (timeout,) if timeout else tuple()
        cls.dispatch = method_decorator(cache_page(*args, **cache_kwargs))(original)
        return cls
    else:
        def _decorator(inner_cls):
            return cache_view(inner_cls, **cache_kwargs)
        return _decorator
Ejemplo n.º 21
0
    def get_urls(self):
        urls = patterns('',
            url(r'^api/marketAdaptor/', include('wirecloud.fiware.marketAdaptor.urls')),
        )

        if IDM_SUPPORT_ENABLED:
            from wirecloud.fiware.views import oauth_discovery
            urls += patterns('',
                url('^.well-known/oauth$', cache_page(7 * 24 * 60 * 60, key_prefix='well-known-oauth-%s' % get_version_hash())(oauth_discovery), name='oauth.discovery'),
            )

        return urls
Ejemplo n.º 22
0
    def as_view(cls, **initkwargs):
        """ Specialised so we can cache view. """
        view = super(BasePageView, cls).as_view(**initkwargs)
        cached_view = cache_page(
            view, settings.PAGE_CACHE_TIME,
            key_prefix=settings.CACHE_KEY_PREFIX)

        logger.debug('called BasePageview.as_view() DEBUG: %s and CACHE_PAGES: %s' % (settings.DEBUG, settings.CACHE_PAGES))

        if not settings.DEBUG and settings.CACHE_PAGES:
            return cached_view
        else:
            return view
Ejemplo n.º 23
0
 def get_allow_handler(self):
     """
     When cache_page is truthy, wraps the base handler in the
     django.views.decorators.cache.cache_page() decorator.
     
     """
     allow = super(CachePage, self).get_allow_handler()
     if self.get_cache_page():
         allow = cache.cache_page(
             self.get_cache_page_timeout(),
             cache=self.get_cache_page_cache(),
             key_prefix=self.get_cache_page_key_prefix())(allow)
     return allow
Ejemplo n.º 24
0
 def get_urls(self):
     urlpatterns = super(FictaApplication, self).get_urls()
     urlpatterns += patterns('',
         url(r'^select/', self.select_view.as_view(),
             name='select'),
         url(r'^(?P<dummyslug>[\w-]+)/(?P<pk>\d+)/$',
             self.detail_view.as_view(), name='detail'),
         url(r'^group/(?P<slug>[\w-]+)/$',
             self.group_view.as_view(), name='group'),
     )
     urlpatterns += patterns('',
         url(r'^person-lookup/', cache_page(60*10)(self.person_lookup_view.as_view()),
             name='person-lookup'),
     )
     return self.post_process_urls(urlpatterns)
Ejemplo n.º 25
0
        def _wrapped_view(request, *args, **kwargs):
            # get request message object
            storage = messages.get_messages(request)

            # if request object hasn't message, cache given view
            if not storage:
                # user auth status
                is_auth = request.user.is_authenticated()

                # if user is authenticated returns "_auth_true_" prefix
                # if not returns "_auth_false_"
                key_prefix = "_auth_%s_" % str(is_auth).lower()

                # return cache_page decorator
                return cache_page(timeout, 
                                  key_prefix=key_prefix)(view_func)(request, *args, **kwargs)
            else:
                # return function without cache_page decorator
                return view_func(request, *args, **kwargs)
Ejemplo n.º 26
0
from django.conf import settings
from django.conf.urls import url, patterns
from django.contrib.sitemaps.views import sitemap
from wazimap.urls import urlpatterns
from wazimap.views import GeographyDetailView
from janaganana.views import TimeseriesDetailView
from django.views.decorators.cache import cache_page

STANDARD_CACHE_TIME = settings.WAZIMAP['cache_secs']

timeseries_url = url(
    regex=
    '^profiles-timeseries/(?P<geography_id>\w+-\w+)(-(?P<slug>[\w-]+))?/$',
    view=cache_page(STANDARD_CACHE_TIME)(TimeseriesDetailView.as_view()),
    kwargs={},
    name='geography_detail2',
)

urlpatterns.append(timeseries_url)
Ejemplo n.º 27
0
    re_path(r'^_administration/viz/chord/(.*)?$', dataviz.d3_views.viz_chord, name='viz_chord'),
    re_path(r'^_administration/viz/steamgraph/(.*)?$', dataviz.d3_views.viz_steamgraph, name='viz_steamgraph'),
    re_path(r'^_administration/viz/circles/(.*)?$', dataviz.d3_views.viz_circles, name='viz_circles'),
    re_path(r'^_administration/viz/sankey/(.*)?$', dataviz.d3_views.viz_sankey, name='viz_sankey'),
    re_path(r'^_administration/viz/spiral/(.*)?$', dataviz.d3_views.viz_spiral, name='viz_spiral'),
    re_path(r'^_administration/viz/heatmap/(.*)?$', dataviz.d3_views.viz_heatmap, name='viz_heatmap'),
    re_path(r'^_administration/viz/calendar/(.*)?$', dataviz.d3_views.viz_calendar, name='viz_calendar'),
    re_path(r'^_administration/viz/draggable/(.*)?$', dataviz.d3_views.viz_draggable, name='viz_draggable'),
    re_path(r'^_administration/viz/scatterplot/(.*)?$', dataviz.d3_views.viz_scatterplot, name='viz_scatterplot'),

    # for robots
    url(r'^robots.txt/?', retail.views.robotstxt, name='robotstxt'),
    path('sitemap.xml', sitemap_index, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.index'),
    path(
        'sitemap-<section>.xml',
        cache_page(86400)(sitemap), {'sitemaps': sitemaps},
        name='django.contrib.sitemaps.views.sitemap'
    ),
    # Interests
    path('interest/modal', dashboard.views.get_interest_modal, name='get_interest_modal'),
    path('actions/bounty/<int:bounty_id>/interest/new/', dashboard.views.new_interest, name='express-interest'),
    path('actions/bounty/<int:bounty_id>/interest/remove/', dashboard.views.remove_interest, name='remove-interest'),
    path(
        'actions/bounty/<int:bounty_id>/interest/<int:profile_id>/uninterested/',
        dashboard.views.uninterested,
        name='uninterested'
    ),

    # Legacy Support
    path('legacy/', include('legacy.urls', namespace='legacy')),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
Ejemplo n.º 28
0
 def dispatch(self, *args, **kwargs):
     return cache_page(self.get_cache_timeout())(super(
         CacheMixin, self).dispatch)(*args, **kwargs)
Ejemplo n.º 29
0
from django.conf.urls.defaults import patterns, url
from django.views.decorators.cache import cache_page
from django.views.generic import DetailView

from models import Event
from views import EventListView

# TODO month view https://github.com/justinlilly/django-gencal or https://github.com/visualspace/django-agenda ?
urlpatterns = patterns(
    '',
    url(r'^$',
        cache_page(60 * 60)(EventListView.as_view()),
        name='events_event_list'),
    url(r'^past/$',
        cache_page(60 * 60)(EventListView.as_view()),
        kwargs={'past': True},
        name='events_event_list_past'),
    url(r'^(?P<pk>\d+)/$',
        DetailView.as_view(model=Event, ),
        name='events_event_detail'),
)
Ejemplo n.º 30
0
    url(r'^$', views.SectionListView.as_view(), name='index'),
    url(r'^new/$',
        never_cache(views.ItemCreateView.as_view()),
        name='item-new'),
    url(r'^edit/(?P<pk>\d+)/$',
        never_cache(views.ItemUpdateView.as_view()),
        name='item-edit'),
    url(r'^(?P<pk>\d+)-(?P<slug>[-\w]+)/$',
        views.ItemDetailView.as_view(),
        name='item'),
    url(r'^group/(?P<pk>\d+)-(?P<slug>[-\w]+)/$',
        views.GroupDetail.as_view(),
        name='group'),
    url(r'^search/', views.SearchView.as_view(), name='search'),
    url(r'^robots\.txt$',
        cache_page(60 * 60)(views.RobotsView.as_view()),
        name='robots'),
    url(r'^sitemap\.xml$',
        sitemap_view, {'sitemaps': sitemap.sitemaps_dict},
        name='sitemap'),
    url(r'^rss\.xml$', cache_page(60 * 15)(feeds.LatestItemFeed()),
        name='rss'),
    url(r'^user/$', views.MyItemsView.as_view(), name='user-items'),
    url(r'^user/profile/$', views.ProfileView.as_view(), name='profile'),
    url(r'^user/my/delete/(?P<pk>\d+)/$',
        views.ItemDeleteView.as_view(),
        name='my-delete'),
    url(r'^complaint/(?P<pk>\d+)-(?P<slug>[-\w]+)/$',
        views.complaint,
        name='complaint'),
]
Ejemplo n.º 31
0
 def _wrapped_view(request, *args, **kwargs):
     key_prefix = "_auth_%s_" % request.user.is_authenticated()
     return cache_page(timeout,
                       key_prefix=key_prefix)(view_func)(request, *args,
                                                         **kwargs)
Ejemplo n.º 32
0
 def as_view(cls, **initkargs):
     view = super(CachePageMixin, cls).as_view(**initkargs)
     return cache_page(60 * 120)(view)
Ejemplo n.º 33
0
class LanguageToolsView(ListAPIView):
    authentication_classes = []
    pagination_class = None
    permission_classes = []
    serializer_class = LanguageToolsSerializer

    @classmethod
    def as_view(cls, **initkwargs):
        """The API is read-only so we can turn off atomic requests."""
        return non_atomic_requests(
            super(LanguageToolsView, cls).as_view(**initkwargs))

    def get_query_params(self):
        """
        Parse query parameters that this API supports:
        - app (mandatory)
        - type (optional)
        - appversion (optional, makes type mandatory)
        - author (optional)

        Can raise ParseError() in case a mandatory parameter is missing or a
        parameter is invalid.

        Returns a dict containing application (int), types (tuple or None),
        appversions (dict or None) and author (string or None).
        """
        # app parameter is mandatory when calling this API.
        try:
            application = AddonAppQueryParam(self.request).get_value()
        except ValueError:
            raise exceptions.ParseError('Invalid or missing app parameter.')

        # appversion parameter is optional.
        if AddonAppVersionQueryParam.query_param in self.request.GET:
            try:
                value = AddonAppVersionQueryParam(self.request).get_values()
                appversions = {'min': value[1], 'max': value[2]}
            except ValueError:
                raise exceptions.ParseError('Invalid appversion parameter.')
        else:
            appversions = None

        # type is optional, unless appversion is set. That's because the way
        # dicts and language packs have their compatibility info set in the
        # database differs, so to make things simpler for us we force clients
        # to filter by type if they want appversion filtering.
        if AddonTypeQueryParam.query_param in self.request.GET or appversions:
            try:
                addon_types = tuple(
                    AddonTypeQueryParam(self.request).get_value())
            except ValueError:
                raise exceptions.ParseError(
                    'Invalid or missing type parameter while appversion '
                    'parameter is set.')
        else:
            addon_types = (amo.ADDON_LPAPP, amo.ADDON_DICT)

        # author is optional. It's a string representing the username(s) we're
        # filtering on.
        if AddonAuthorQueryParam.query_param in self.request.GET:
            author = AddonAuthorQueryParam(self.request).get_value()
        else:
            author = None

        return {
            'application': application,
            'types': addon_types,
            'appversions': appversions,
            'author': author,
        }

    def get_queryset(self):
        """
        Return queryset to use for this view, depending on query parameters.
        """
        # application, addon_types, appversions
        params = self.get_query_params()
        if params['types'] == (amo.ADDON_LPAPP, ) and params['appversions']:
            qs = self.get_language_packs_queryset_with_appversions(
                params['application'], params['appversions'])
        else:
            # appversions filtering only makes sense for language packs only,
            # so it's ignored here.
            qs = self.get_queryset_base(params['application'], params['types'])

        if params['author']:
            qs = qs.filter(addonuser__user__username__in=params['author'],
                           addonuser__listed=True).distinct()
        return qs

    def get_queryset_base(self, application, addon_types):
        """
        Return base queryset to be used as the starting point in both
        get_queryset() and get_language_packs_queryset_with_appversions().
        """
        return (
            Addon.objects.public().filter(
                appsupport__app=application,
                type__in=addon_types,
                target_locale__isnull=False).exclude(target_locale='')
            # Deactivate default transforms which fetch a ton of stuff we
            # don't need here like authors, previews or current version.
            # It would be nice to avoid translations entirely, because the
            # translations transformer is going to fetch a lot of translations
            # we don't need, but some language packs or dictionaries have
            # custom names, so we can't use a generic one for them...
            .only_translations()
            # Since we're fetching everything with no pagination, might as well
            # not order it.
            .order_by())

    def get_language_packs_queryset_with_appversions(self, application,
                                                     appversions):
        """
        Return queryset to use specifically when requesting language packs
        compatible with a given app + versions.

        application is an application id, and appversions is a dict with min
        and max keys pointing to application versions expressed as ints.
        """
        # Base queryset.
        qs = self.get_queryset_base(application, (amo.ADDON_LPAPP, ))
        # Version queryset we'll prefetch once for all results. We need to
        # find the ones compatible with the app+appversion requested, and we
        # can avoid loading translations by removing transforms and then
        # re-applying the default one that takes care of the files and compat
        # info.
        versions_qs = (Version.objects.latest_public_compatible_with(
            application,
            appversions).no_transforms().transform(Version.transformer))
        return (qs.prefetch_related(
            Prefetch(
                'versions',
                to_attr='compatible_versions',
                queryset=versions_qs)).filter(
                    versions__apps__application=application,
                    versions__apps__min__version_int__lte=appversions['min'],
                    versions__apps__max__version_int__gte=appversions['max'],
                    versions__channel=amo.RELEASE_CHANNEL_LISTED,
                    versions__files__status=amo.STATUS_PUBLIC).distinct())

    @method_decorator(cache_page(60 * 60 * 24))
    def dispatch(self, *args, **kwargs):
        return super(LanguageToolsView, self).dispatch(*args, **kwargs)

    def list(self, request, *args, **kwargs):
        # Ignore pagination (return everything) but do wrap the data in a
        # 'results' property to mimic what the default implementation of list()
        # does in DRF.
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({'results': serializer.data})
Ejemplo n.º 34
0
sitemaps = {
    'dominio': DominioSitemap,
    'registrante': RegistranteSitemap,
    'rubro': RubroSitemap,
    'hosting': HostingSitemap,
    'dns': DNSSitemap
}

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls')),
    path('api/', include('djnic.api.urls')),
    path('api-token-auth/', views.obtain_auth_token),
    # Sitemap https://docs.djangoproject.com/en/3.1/ref/contrib/sitemaps/#creating-a-sitemap-index
    path('sitemap.xml',
         cache_page(86400)(sitemap_views.index), {'sitemaps': sitemaps}),
    path('sitemap-<section>.xml',
         cache_page(86400)(sitemap_views.sitemap), {'sitemaps': sitemaps},
         name='django.contrib.sitemaps.views.sitemap'),

    # webpush
    path('webpush/', include('webpush.urls')),

    # all auth
    path('accounts/', include('allauth.urls')),

    # all website
    path('', include('web.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Ejemplo n.º 35
0
                                           never_cache)
from django.views.decorators.csrf import ensure_csrf_cookie

from . import views
from .decorators import (jsonize_view, login_required_if_not_anonymous_allowed,
                         map_permissions_check)
from .utils import decorated_patterns

admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url('', include('social_django.urls', namespace='social')),
    url(r'^m/(?P<pk>\d+)/$', views.MapShortUrl.as_view(),
        name='map_short_url'),
    url(r'^ajax-proxy/$', cache_page(180)(views.ajax_proxy),
        name='ajax-proxy'),
    url(r'^change-password/',
        auth_views.password_change,
        {'template_name': 'umap/password_change.html'},
        name='password_change'),
    url(r'^change-password-done/',
        auth_views.password_change_done,
        {'template_name': 'umap/password_change_done.html'},
        name='password_change_done'),
    url(r'^i18n/', include('django.conf.urls.i18n')),
    url(r'^agnocomplete/', include('agnocomplete.urls')),
]

i18n_urls = [
    url(r'^login/$', jsonize_view(login), name='login'),  # noqa
Ejemplo n.º 36
0
from django.views.generic import TemplateView
from django.views.decorators.cache import cache_page

class HomeView(TemplateView):
    template_name = 'pages/home.html'

home = cache_page(60 * 10)(HomeView.as_view())
Ejemplo n.º 37
0
from django.conf.urls import url
from . import views
from django.views.decorators.cache import cache_page

urlpatterns = [
    url(r'^register/$', views.StudentRegstrationView.as_view(), name='student_registration'),
    url(r'^enroll-course/$', views.StudentEnrollCourseView.as_view(), name='student_enroll_course'),
    url(r'^courses/$', views.StudentCourseListView.as_view(), name='student_course_list'),
    url(r'^course/(?P<pk>\d+)/$', cache_page(60 * 15)(views.StudentCourseDetailView.as_view()), name='student_course_detail'),
    url(r'^course/(?P<pk>\d+)/(?P<module_id>\d+)/$', cache_page(60*15)(views.StudentCourseDetailView.as_view()), name='student_course_detail_module'),
]
Ejemplo n.º 38
0

full_decorator = compose(
    # django.views.decorators.http
    require_http_methods(["GET"]),
    require_GET,
    require_POST,
    require_safe,
    condition(lambda r: None, lambda r: None),

    # django.views.decorators.vary
    vary_on_headers('Accept-language'),
    vary_on_cookie,

    # django.views.decorators.cache
    cache_page(60 * 15),
    cache_control(private=True),
    never_cache,

    # django.contrib.auth.decorators
    # Apply user_passes_test twice to check #9474
    user_passes_test(lambda u: True),
    login_required,
    permission_required('change_world'),

    # django.contrib.admin.views.decorators
    staff_member_required,

    # django.utils.functional
    lambda f: memoize(f, {}, 1),
    allow_lazy,
Ejemplo n.º 39
0
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.mail import send_mail
from django.http import JsonResponse
from django.shortcuts import redirect
from django.template.loader import render_to_string
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.generic import CreateView, DeleteView, DetailView, ListView, UpdateView

from .forms import FeedbackFrom
from .models import Student, University


@method_decorator(cache_page(10), name='dispatch')
class StudentList(ListView):
    model = Student
    paginate_by = 10
    template_name = 'university/student_list_page.html'
    ordering = ['first_name', 'last_name']


@method_decorator(cache_page(10), name='dispatch')
class StudentDetail(DetailView):
    model = Student
    template_name = 'university/student_detail_page.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context
Ejemplo n.º 40
0
STANDARD_CACHE_TIME = getattr(settings, 'CACHE_MIDDLEWARE_SECONDS', 60 * 15)
FEED_CACHE_TIME = getattr(settings, 'FEED_CACHE_SECONDS', 60 * 15)

urlpatterns = patterns(
    '',
    # /articles/ is matched as a section in base.urls
    #url(
    #    regex = '^$',
    #    view = ArticleList.as_view(),
    #    kwargs = {},
    #   name = 'article_list',
    #,
    url(
        regex='^tags/(?P<tag_slugs>[-\w\+]+)/$',
        view=cache_page(ArticleList.as_view(), STANDARD_CACHE_TIME),
        kwargs={},
        name='article_list_by_tag',
    ),
    url(
        regex='^tags/(?P<tag_slugs>[-\w\+]+)/rss/$',
        view=cache_page(ArticleFeed(), FEED_CACHE_TIME),
        kwargs={},
        name='article_list_by_tag_feed',
    ),
    url(
        regex='^tags/$',
        view=redirect_to,
        kwargs={'url': '/articles/'},
        name='article_list_tags',
    ),
Ejemplo n.º 41
0
from dashboard.views.interfacetext_view import InterfaceTextView
from dashboard.views.officer_view import AdminOfficerViewSet
from dashboard.views.query_data_view import AdminQueryDataApi
from dashboard.views.search_traffic import AdminSearchTrafficApi
from dashboard.views.sessions_view import AdminSessionsView
from dashboard.views.story_view import AdminStoryViewSet
from dashboard.views.settings_view import AdminSettingsView
from dashboard.views.document_request_status_view import DocumentRequestStatusView
from dashboard.views.document_link_view import DocumentLinkView
from dashboard.views.story_type_view import StoryTypeView
from dashboard.views.admin_session_analytics_view import AdminNewSessionsAnalyticsViewSet
from dashboard.views.admin_session_alias_view import AdminSessionAliasApi, AdminSessionsAliasViewSet
from dashboard.views.admin_investigation_documents_export_view import AdminInvestigationDocumentsExportView
from dashboard.views.admin_document_upload_view import AdminDocumentUploadView

cache_view = cache_page(86400 * 90)

router = routers.DefaultRouter()
router.register(r'officers', AdminOfficerViewSet)
router.register(r'stories', AdminStoryViewSet)
router.register(r'document-requests', AdminAllegationRequestViewSet)
router.register(r'sessions', AdminSessionsView)
router.register(r'session-alias2', AdminSessionsAliasViewSet)
router.register(r'new-sessions-analytics', AdminNewSessionsAnalyticsViewSet)
router.register(r'settings', AdminSettingsView)
router.register(r'interface-texts', InterfaceTextView)

urlpatterns = [
    url(r'^api/dashboard/search-traffic/$',
        login_required(AdminSearchTrafficApi.as_view()),
        name='dashboard-search-traffic'),
Ejemplo n.º 42
0
from django.views.decorators.cache import cache_page

from django_mongoengine.views import TemplateView

from . import views

urlpatterns = patterns(
    '',

    # TemplateView
    (r'^template/no_template/$', TemplateView.as_view()),
    (r'^template/simple/(?P<foo>\w+)/$',
     TemplateView.as_view(template_name='views/about.html')),
    (r'^template/custom/(?P<foo>\w+)/$',
     views.CustomTemplateView.as_view(template_name='views/about.html')),
    (r'^template/cached/(?P<foo>\w+)/$', cache_page(2.0)(
        TemplateView.as_view(template_name='views/about.html'))),

    # DetailView
    (r'^detail/obj/$', views.ObjectDetail.as_view()),
    url(r'^detail/artist/(?P<pk>\d+)/$',
        views.ArtistDetail.as_view(),
        name="artist_detail"),
    url(r'^detail/author/(?P<pk>\d+)/$',
        views.AuthorDetail.as_view(),
        name="author_detail"),
    (r'^detail/author/bycustompk/(?P<foo>\d+)/$',
     views.AuthorDetail.as_view(pk_url_kwarg='foo')),
    (r'^detail/author/byslug/(?P<slug>[\w-]+)/$',
     views.AuthorDetail.as_view()),
    (r'^detail/author/bycustomslug/(?P<foo>[\w-]+)/$',
     views.AuthorDetail.as_view(slug_url_kwarg='foo')),
Ejemplo n.º 43
0
flatpage_sitemaps = {
    'flatpages': FlatPageSitemap,
}

urlpatterns = patterns(
    'django.contrib.sitemaps.views', (r'^simple/index\.xml$', 'index', {
        'sitemaps': simple_sitemaps
    }), (r'^simple/custom-index\.xml$', 'index', {
        'sitemaps': simple_sitemaps,
        'template_name': 'custom_sitemap_index.xml'
    }), (r'^simple/sitemap-(?P<section>.+)\.xml$', 'sitemap', {
        'sitemaps': simple_sitemaps
    }), (r'^simple/sitemap\.xml$', 'sitemap', {
        'sitemaps': simple_sitemaps
    }), (r'^simple/custom-sitemap\.xml$', 'sitemap', {
        'sitemaps': simple_sitemaps,
        'template_name': 'custom_sitemap.xml'
    }), (r'^generic/sitemap\.xml$', 'sitemap', {
        'sitemaps': generic_sitemaps
    }), (r'^flatpages/sitemap\.xml$', 'sitemap', {
        'sitemaps': flatpage_sitemaps
    }),
    url(r'^cached/index\.xml$',
        cache_page(1)(views.index), {
            'sitemaps': simple_sitemaps,
            'sitemap_url_name': 'cached_sitemap'
        }),
    url(r'^cached/sitemap-(?P<section>.+)\.xml',
        cache_page(1)(views.sitemap), {'sitemaps': simple_sitemaps},
        name='cached_sitemap'))
Ejemplo n.º 44
0
from django.urls import path
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView

from . import views

app_name = 'netzkarte'
urlpatterns = [
    path('',
         TemplateView.as_view(template_name="netzkarte/index.html"),
         name='index'),
    path('api', views.convert_toJson, name='api'),
    path('d3api', cache_page(60 * 120)(views.d3_tree), name='d3api'),
]
Ejemplo n.º 45
0
def old_patterns():
    return [
        # DALITE
        # Assignment table of contents - Enforce sameorigin to prevent access from LMS  # noqa
        url(
            r"^browse/$",
            xframe_options_sameorigin(views.browse_database),
            name="browse-database",
        ),
        url(
            r"^assignment-list/$",
            xframe_options_sameorigin(views.AssignmentListView.as_view()),
            name="assignment-list",
        ),
        url(
            r"^question/create$",
            views.QuestionCreateView.as_view(),
            name="question-create",
        ),
        url(
            r"^question/clone/(?P<pk>[0-9]+)$",
            views.QuestionCloneView.as_view(),
            name="question-clone",
        ),
        url(
            r"^question/update/(?P<pk>[0-9]+)$",
            views.QuestionUpdateView.as_view(),
            name="question-update",
        ),
        url(
            r"^question/delete", views.question_delete, name="question-delete"
        ),
        url(
            r"^discipline/create$",
            views.DisciplineCreateView.as_view(),
            name="discipline-create",
        ),
        url(
            r"^discipline/form/(?P<pk>[0-9]+)$",
            views.discipline_select_form,
            name="discipline-form",
        ),
        url(
            r"^discipline/form$",
            views.discipline_select_form,
            name="discipline-form",
        ),
        url(
            r"^disciplines/create$",
            views.DisciplinesCreateView.as_view(),
            name="disciplines-create",
        ),
        url(
            r"^disciplines/form$",
            views.disciplines_select_form,
            name="disciplines-form",
        ),
        url(
            r"^category/create$",
            views.CategoryCreateView.as_view(),
            name="category-create",
        ),
        url(
            r"^category/form/(?P<pk>[0-9]+)$",
            views.category_select_form,
            name="category-form",
        ),
        url(
            r"^category/form$",
            views.category_select_form,
            name="category-form",
        ),
        url(
            r"^answer-choice/form/(?P<question_id>[0-9]+)$",
            views.answer_choice_form,
            name="answer-choice-form",
        ),
        url(
            r"^sample-answer/form/(?P<question_id>[0-9]+)$",
            admin_views.QuestionPreviewViewBase.as_view(),
            name="sample-answer-form",
        ),
        url(
            r"^sample-answer/form/(?P<question_id>[0-9]+)/done$",
            views.sample_answer_form_done,
            name="sample-answer-form-done",
        ),
        url(
            r"^assignment/copy/(?P<assignment_id>[^/]+)$",
            views.AssignmentCopyView.as_view(),
            name="assignment-copy",
        ),
        url(
            r"^assignment/edit$",
            views.update_assignment_question_list,
            name="assignment-edit-ajax",
        ),
        url(
            r"^assignment/edit/(?P<assignment_id>[^/]+)$",
            views.AssignmentEditView.as_view(),
            name="assignment-edit",
        ),
        url(
            r"^question-search/$",
            views.question_search,
            name="question-search",
        ),
        url(r"^heartbeat/$", views.HeartBeatUrl.as_view(), name="heartbeat"),
        url(
            r"^collection/create$",
            views.CollectionCreateView.as_view(),
            name="collection-create",
        ),
        # Standalone
        url(
            r"^live/access/(?P<token>[0-9A-Za-z=_-]+)/(?P<assignment_hash>[0-9A-Za-z=_-]+)$",  # noqa
            views.live,
            name="live",
        ),
        url(
            r"^live/navigate/(?P<assignment_id>[^/]+)/(?P<question_id>\d+)/(?P<direction>(next|prev|goto))/(?P<index>[0-9x]+)$",  # noqa
            views.navigate_assignment,
            name="navigate-assignment",
        ),
        url(
            r"^live/signup/form/(?P<group_hash>[0-9A-Za-z=_-]+)$",
            views.signup_through_link,
            name="signup-through-link",
        ),
        url(
            r"^live/studentgroupassignment/create/(?P<assignment_id>[^/]+)$",
            views.StudentGroupAssignmentCreateView.as_view(),
            name="student-group-assignment-create",
        ),
        # Admin
        url(r"^dashboard/$", views.dashboard, name="dashboard"),
        url(
            r"^admin/$",
            admin_views.AdminIndexView.as_view(),
            name="admin-index",
        ),
        url(
            r"^admin/peerinst/",
            include(
                [
                    url(
                        r"^assignment_results/(?P<assignment_id>[^/]+)/",
                        include(
                            [
                                url(
                                    r"^$",
                                    admin_views.AssignmentResultsView.as_view(),  # noqa
                                    name="assignment-results",
                                ),
                                url(
                                    r"^rationales/(?P<question_id>\d+)$",
                                    admin_views.QuestionRationaleView.as_view(),  # noqa
                                    name="question-rationales",
                                ),
                            ]
                        ),
                    ),
                    url(
                        r"^question_preview/(?P<question_id>[^/]+)$",
                        admin_views.QuestionPreviewView.as_view(),
                        name="question-preview",
                    ),
                    url(
                        r"^fake_usernames/$",
                        admin_views.FakeUsernames.as_view(),
                        name="fake-usernames",
                    ),
                    url(
                        r"^fake_countries/$",
                        admin_views.FakeCountries.as_view(),
                        name="fake-countries",
                    ),
                    url(
                        r"^attribution_analysis/$",
                        admin_views.AttributionAnalysis.as_view(),
                        name="attribution-analysis",
                    ),
                    url(
                        r"^group_assignment_management/$",
                        admin_views.StudentGroupAssignmentManagement.as_view(),
                        name="group-assignment-management",
                    ),
                ]
            ),
        ),
        # Teachers
        url(
            r"^teacher-account/(?P<pk>[0-9]+)/$",
            views.TeacherDetailView.as_view(),
            name="teacher",
        ),
        url(
            r"^teacher/(?P<pk>[0-9]+)/$",
            views.TeacherUpdate.as_view(),
            name="teacher-update",
        ),
        url(
            r"^teacher/(?P<pk>[0-9]+)/assignments/$",
            views.TeacherAssignments.as_view(),
            name="teacher-assignments",
        ),
        url(
            r"^teacher/(?P<pk>[0-9]+)/blinks/$",
            views.TeacherBlinks.as_view(),
            name="teacher-blinks",
        ),
        url(
            r"^teacher/favourite",
            views.teacher_toggle_favourite,
            name="teacher-toggle-favourite",
        ),
        url(
            r"^teacher/(?P<pk>[0-9]+)/groups/$",
            views.TeacherGroups.as_view(),
            name="teacher-groups",
        ),
        url(
            r"^teacher/(?P<pk>[0-9]+)/group/(?P<group_hash>[0-9A-Za-z=_-]+)/share$",  # noqa
            views.TeacherGroupShare.as_view(),
            name="group-share",
        ),
        url(
            r"^teacher/(?P<teacher_id>[0-9]+)/group_assignments/$",
            views.StudentGroupAssignmentListView.as_view(),
            name="group-assignments",
        ),
        url(
            r"^teacher/student_activity/$",
            views.student_activity,
            name="student-activity",
        ),
        url(
            r"^teacher/report/all_groups/(?P<assignment_id>[^/]+)/$",
            views.report,
            name="report-all-groups",
        ),
        url(
            r"^teacher/report/all_assignments/(?P<group_id>[^/]+)/$",
            views.report,
            name="report-all-assignments",
        ),
        url(
            r"^teacher/report_selector$",
            views.report_selector,
            name="report_selector",
        ),
        url(r"^teacher/custom_report/$", views.report, name="report-custom"),
        url(
            r"^report_rationales_chosen$",
            views.report_assignment_aggregates,
            name="report_rationales_chosen",
        ),
        # Auth
        url(r"^$", views.landing_page, name="landing_page"),
        url(r"^signup/$", views.sign_up, name="sign_up"),
        url(
            r"^login/$",
            user_passes_test(not_authenticated, login_url="/welcome/")(
                auth_views.login
            ),
            name="login",
        ),
        url(r"^logout/$", views.logout_view, name="logout"),
        url(r"^welcome/$", views.welcome, name="welcome"),
        # Only non-students can change their password
        url(
            r"^password_change/$",
            user_passes_test(student_check)(password_views.password_change),
            name="password_change",
        ),
        url(
            r"^password_change/done/$",
            auth_views.password_change_done,
            name="password_change_done",
        ),
        url(
            r"^password_reset/$",
            auth_views.password_reset,
            {
                "html_email_template_name": "registration/password_reset_email_html.html",  # noqa
                "password_reset_form": NonStudentPasswordResetForm,
            },
            name="password_reset",
        ),
        url(
            r"^password_reset/done/$",
            auth_views.password_reset_done,
            name="password_reset_done",
        ),
        url(
            r"^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$",  # noqa
            password_views.password_reset_confirm,
            name="password_reset_confirm",
        ),
        url(
            r"^reset/done/$",
            auth_views.password_reset_complete,
            name="password_reset_complete",
        ),
        url(
            r"^terms_of_service/teachers/$",
            views.terms_teacher,
            name="terms_teacher",
        ),
        url(r"^access_denied/$", views.access_denied, name="access_denied"),
        url(
            r"^access_denied_and_logout/$",
            views.access_denied_and_logout,
            name="access_denied_and_logout",
        ),
        # Blink
        url(
            r"^blink/(?P<pk>[0-9]+)/$",
            views.BlinkQuestionFormView.as_view(),
            name="blink-question",
        ),
        url(
            r"^blink/(?P<pk>[0-9]+)/summary/$",
            views.BlinkQuestionDetailView.as_view(),
            name="blink-summary",
        ),
        url(
            r"^blink/(?P<pk>[0-9]+)/count/$",
            views.blink_count,
            name="blink-count",
        ),
        url(
            r"^blink/(?P<pk>[0-9]+)/close/$",
            views.blink_close,
            name="blink-close",
        ),
        url(
            r"^blink/(?P<pk>[0-9]+)/latest_results/$",
            views.blink_latest_results,
            name="blink-results",
        ),
        url(
            r"^blink/(?P<pk>[0-9]+)/reset/$",
            views.blink_reset,
            name="blink-reset",
        ),
        url(
            r"^blink/(?P<pk>[0-9]+)/status/$",
            views.blink_status,
            name="blink-status",
        ),
        url(
            r"^blink/(?P<username>[\w.@+-]+)/$",
            views.blink_get_current,
            name="blink-get-current",
        ),
        url(
            r"^blink/(?P<username>[\w.@+-]+)/url/$",
            cache_page(1)(views.blink_get_current_url),
            name="blink-get-current-url",
        ),
        url(
            r"^blink/(?P<pk>[0-9]+)/get_next/$",
            views.blink_get_next,
            name="blink-get-next",
        ),
        url(
            r"^blink/waiting/(?P<username>[\w.@+-]+)/$",
            views.blink_waiting,
            name="blink-waiting",
        ),
        url(
            r"^blink/waiting/(?P<username>[\w.@+-]+)/(?P<assignment>[0-9]+)/$",
            views.blink_waiting,
            name="blink-waiting",
        ),
        url(
            r"^blinkAssignment/create/$",
            views.BlinkAssignmentCreate.as_view(),
            name="blinkAssignment-create",
        ),
        url(
            r"^blinkAssignment/(?P<pk>[0-9]+)/delete/$",
            views.blink_assignment_delete,
            name="blinkAssignment-delete",
        ),
        url(
            r"^blinkAssignment/(?P<pk>[0-9]+)/set_time/$",
            views.blink_assignment_set_time,
            name="blinkAssignment-set-time",
        ),
        url(
            r"^blinkAssignment/(?P<pk>[0-9]+)/start/$",
            views.blink_assignment_start,
            name="blinkAssignment-start",
        ),
        url(
            r"^blinkAssignment/(?P<pk>[0-9]+)/update/$",
            views.BlinkAssignmentUpdate.as_view(),
            name="blinkAssignment-update",
        ),
    ]
Ejemplo n.º 46
0
from dv_apps.metrics.stats_util_base import StatsMakerBase


def send_cors_response(response):
    """Quick hack to allow CORS...."""

    response["Access-Control-Allow-Origin"] = "*"
    #response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    #response["Access-Control-Max-Age"] = "1000"
    #response["Access-Control-Allow-Headers"] = "*"

    return response


#@method_decorator(apikey_required, name='get')
@method_decorator(cache_page(get_metrics_api_cache_time()), name='get')
class StatsViewSwagger(View):
    """Used to help build the swagger docs"""

    # params getting a bit out of control, need to make this more manageable

    BASIC_DATE_PARAMS = ['startDateParam', 'endDateParam', 'selectedYearParam']

    PARAM_DV_API_KEY = ['dataverseAPIKey']
    PARAM_SELECTED_DV_ALIASES = ['selectedDataverseAliases']
    PARAM_INCLUDE_CHILD_DVS = ['includeChildDataverses']
    PARAM_AS_CSV = ['asCSV', 'asExcel']

    PARAM_BIN_SIZE = ['binSize']  # bin_size
    PARAM_BIN_SIZE_BYTES = ['binSizeBytes']  # bin_size
Ejemplo n.º 47
0
# -*- coding: utf-8 -*-

from django.conf.urls.defaults import include
from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url
from django.views.decorators.cache import cache_page
from pythonkc_site.views import PythonKCHome

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r'^/?$', cache_page(60 * 5)(PythonKCHome.as_view()), name='home'),

    # Examples:
    # url(r'^$', 'pythonkc_site.views.home', name='home'),
    # url(r'^pythonkc_site/', include('pythonkc_site.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
)
Ejemplo n.º 48
0
 def _wrapped_view(request, *args, **kwargs):
     if request.user.is_authenticated() or messages.get_messages(
             request):
         return view_func(request, *args, **kwargs)
     else:
         return cache_page(timeout)(view_func)(request, *args, **kwargs)
Ejemplo n.º 49
0
 def dispatch(self, request, *args, **kwargs):
     return cache_page(
         self.get_timeout(),
         key_prefix=self.cache_key
     )(super().dispatch)(request, *args, **kwargs)
Ejemplo n.º 50
0
 ),
 path(
     "js/ignore-check/<int:check_id>/",
     weblate.trans.views.js.ignore_check,
     name="js-ignore-check",
 ),
 path(
     "js/ignore-check/<int:check_id>/source/",
     weblate.trans.views.js.ignore_check_source,
     name="js-ignore-check-source",
 ),
 path(
     "js/i18n/",
     cache_page(3600)(
         vary_on_cookie(
             django.views.i18n.JavaScriptCatalog.as_view(packages=["weblate"])
         )
     ),
     name="js-catalog",
 ),
 path("js/matomo/", weblate.trans.views.js.matomo, name="js-matomo"),
 path(
     "js/translate/<name:service>/<int:unit_id>/",
     weblate.trans.views.js.translate,
     name="js-translate",
 ),
 path(
     "js/memory/<int:unit_id>/",
     weblate.trans.views.js.memory,
     name="js-memory",
 ),
Ejemplo n.º 51
0
    ClienteDeleteView,
    PedidosListView,
    PedidoListView,
    PedidoCreateView,
    PedidoUpdateView,
    PedidoDeleteView,
    ItemCreateView,
)

CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)

urlpatterns = [
    path('', EcommerceView.as_view(), name='index'),
    #PRODUTOS
    path('produtos/',
         cache_page(CACHE_TTL)(ProdutoListView.as_view()),
         name='produtos'),
    path('produtos/create/', ProdutoCreateView.as_view(),
         name='produtoCreate'),
    path('produtos/<int:pk>/edit/',
         ProdutoUpdateView.as_view(),
         name='produtoEdit'),
    path('produtos/<int:pk>/delete/',
         ProdutoDeleteView.as_view(),
         name='produtoDelete'),
    #CLIENTES
    path('clientes/',
         cache_page(CACHE_TTL)(ClienteListView.as_view()),
         name='clientes'),
    path('clientes/create/', ClienteCreateView.as_view(),
         name='clienteCreate'),
Ejemplo n.º 52
0
    url(r'^tag/(?P<tag_id>\d+)/$', TagView.as_view(), name='tag-list'),
    url(r'^post/(?P<post_id>\d+).html$',
        PostDetailView.as_view(),
        name='post-detail'),
    url(r'^links/$', LinkListView.as_view(), name='links'),
    # url(r'^super_admin/', admin.site.urls,name='super-admin'),
    url(r'^admin/', xadmin.site.urls, name='xadmin'),
    url(r'^aurl/', aurl, name='aurl'),
    url(r'^search/$', SearchView.as_view(), name='search'),
    url(r'^author/(?P<owner_id>\d+)/$', AuthorView.as_view(), name='author'),
    url(r'^comment/$', CommentView.as_view(), name='comment'),
    url(r'^rss|feed/', LatestPostFeed(), name='rss'),
    # url(r'^sitemap\.xml$', sitemap_views.sitemap,{'sitemaps':{'posts':PostSitemap}}),
    url(
        r'^sitemap\.xml$',
        cache_page(60 * 20, key_prefix='sitemap_cache_')(
            sitemap_views.sitemap), {'sitemaps': {
                'posts': PostSitemap
            }}),
    url(r'^category-autocomplete/$',
        CategoryAutocomplete.as_view(),
        name='category-autocomplete'),
    url(r'^tag-autocomplete/$',
        TagAutocomplete.as_view(),
        name='tag-autocomplete'),
    url(r'^ckeditor/', include('ckeditor_uploader.urls')),
    # url(r'^api/post/',PostList.as_view(),name='post-list'),
    # url(r'^api/post/',post_list,name='post-list'),
    url(r'^api/', include(router.urls)),
    url(r'^api/docs/', include_docs_urls(title='typeidea apis')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Ejemplo n.º 53
0
     GastroSignupView.as_view(),
     name='gastro-signups-detail-restricted'
 ),
 path(
     'newsletter-signup',
     newsletter_signup,
     name='newsletter-signup'
 ),
 path(
     'profiles/<str:profile_id>',
     profile,
     name='profile-detail'
 ),
 path(
     'projects',
     cache_page(60 * 60 * 4)(ProjectList.as_view()),
     name='project-list'
 ),
 path(
     'projects/<int:pk>',
     ProjectDetail.as_view(),
     name='project-detail'
 ),
 path(
     'projects/<int:pk>/likes',
     LikeView.as_view(),
     {'model': Project},
     name='likes-projects'
 ),
 path(
     'sections',
Ejemplo n.º 54
0
from django.urls import path
from . import views
from django.views.decorators.cache import cache_page
urlpatterns = [
    path('register/', views.StudentRegistrationView.as_view(), name='student_registration'),
    path('enroll-course/', views.StudentEnrollCourseView.as_view(), name='student_enroll_course'),
    path('courses/', views.StudentCourseListView.as_view(), name='student_course_list'),
    path('course/<pk>/', cache_page(60*15)(views.StudentCourseDetailView.as_view()), name='student_course_detail'),
    path('course/<pk>/<module_id>/', cache_page(60*15)(views.StudentCourseDetailView.as_view()), name='student_course_detail_module'),
]
Ejemplo n.º 55
0
        title = "Creating new page"
    
    if request.POST:
        form = PageForm( request.POST, instance = page )
        if form.is_valid():
            page = form.save()
            return HttpResponseRedirect( "/edit/%s/"%page.id  )

    else:
        form = PageForm( instance = page )
    
    return render('edit.html', locals() )

def error(request, err):
    return render('%s.html'%err, locals() )
    

if settings.CACHE_PAGES:
    all_tags = cache_page(all_tags, 60 * 100)
    appcast = cache_page( appcast, 60 * 10 )
    day = cache_page(day, 60 * 5 )
    month = cache_page(month, 60 * 5 )
    pagetype = cache_page(pagetype, 60 * 5 )
    tag = cache_page(tag, 60 * 5 )
    tag_feed = cache_page( tag_feed, 60 * 100 )
    year = cache_page(year, 60 * 100 )
    stream = cache_page(stream, 60 )

    #datepage = cache_page(datepage, 60 * 1)
    #slugpage = cache_page(slugpage, 60 * 1)
Ejemplo n.º 56
0
class CachedViewMixin:
    @method_decorator(cache_page(settings.CACHE_MIDDLEWARE_SECONDS))
    def get(self, request, *args, **kwargs):
        return super().get(request, *args, **kwargs)
Ejemplo n.º 57
0
Archivo: urls.py Proyecto: Brozzy/kuma
    ('', include('landing.urls')),
    ('', include('devmo.urls')),
    (r'^demos/', include('demos.urls')),
    (r'^demos', lambda x: redirect('demos')),

    # Django admin:
    (r'^grappelli/', include('grappelli.urls')),
    (r'^admin/', include('smuggler.urls')),
    (r'^admin/', include(admin.site.urls)),

    (r'^search', include('search.urls')),

    (r'^docs', include('wiki.urls')),

    # Javascript translations.
    url(r'^jsi18n/.*$', cache_page(60 * 60 * 24 * 365)(javascript_catalog),
        {'domain': 'javascript', 'packages': [settings.ROOT_PACKAGE]},
        name='jsi18n'),

    url(r'^', include('dashboards.urls')),

    # Files.
    url(r'^files/new/$',
        'wiki.views.new_attachment',
        name='wiki.new_attachment'),
    url(r'^files/(?P<attachment_id>\d+)/$',
        'wiki.views.attachment_detail',
        name='wiki.attachment_detail'),
    url(r'^files/(?P<attachment_id>\d+)/edit/$',
        'wiki.views.edit_attachment',
        name='wiki.edit_attachment'),
Ejemplo n.º 58
0
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from . import views

app_name = 'app'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    # (?P<article_id>\d+), ?P<article_di>article_id
    url(r'^article/(?P<article_id>\d+)$', cache_page(60 * 15)(views.ArticleDetailView.as_view()), name='detail'),
    url(r"^category/(?P<cate_id>\d+)$", views.CategoryView.as_view(), name='category'),
    url(r'^article/(?P<article_id>\d+)/comment/$', views.CommentView, name='comment'),
    url(r'^search/$', views.blog_search, name='search'),
    url(r'^about_me/$', views.suggest_view, name='about_me'),
    url(r'^tags/(?P<tag_id>\d+)$', views.TagView.as_view(), name='tag'),
    url(r'^thanks/$', views.thanks, name='thanks')
]
Ejemplo n.º 59
0
Archivo: views.py Proyecto: zokis/TG
            'oco_abertas_100': oco_abertas_100,
            'oco_inapropriadas': oco_inapropriadas,
            'oco_inapropriadas_100': oco_inapropriadas_100,
            'oco_reabertas': oco_reabertas,
            'oco_reabertas_100': oco_reabertas_100,
            'oco_resolvidas': oco_resolvidas,
            'oco_resolvidas_100': oco_resolvidas_100,
            'oco_spam': oco_spam,
            'oco_spam_100': oco_spam_100,
            'oco_total': oco_total,
            'ocos_cats': ocos_cats,
            'users': users,
        })
        return context

estatisticas = cache_page(60 * 25)(EstatisticasView.as_view())


def contact(request):
    form = ContatoForm(request.GET or None)
    return render_to_response(
        'contact.html',
        {
            'form': form,
            'user': request.user,
            'title': u'Contato'
        }
    )


class AboutView(TemplateView):
Ejemplo n.º 60
0
CACHE_MINUTES_SECS = 60 * 5  # minutes
CACHE_DAYS_SECS = 60 * 60 * 24 * 5  # days


def permission_denied(request):
    raise PermissionDenied()


def trigger_error(request):
    division_by_zero = 1 / 0


department_urlpatterns = [
    url(r"^$",
        cache_page(CACHE_MINUTES_SECS)(views.department_page),
        name="department"),
    url(
        r"^viz/subprog-treemap$",
        cache_page(CACHE_DAYS_SECS)(views.department_viz_subprog_treemap),
        name="department-viz-subprog-treemap",
    ),
    url(
        r"^viz/subprog-econ4-circles$",
        cache_page(CACHE_DAYS_SECS)(
            views.department_viz_subprog_econ4_circles),
        name="department-viz-subprog-econ4-circles",
    ),
    url(
        r"^viz/subprog-econ4-bars$",
        cache_page(CACHE_DAYS_SECS)(views.department_viz_subprog_econ4_bars),