def test_apply_to_class_based_view(self): @self.registry.register(allow_anonymous=True) def can_do_things(user): return user.can_do_things @self.registry.require('can_do_things') class View(object): def dispatch(self, req): return getattr(self, req.method.lower())(req) def get(self, req): pass self.assertEqual(View.dispatch.__name__, 'dispatch') request = self.request_factory.get('/things') request.user = User() request.user.can_do_things = True view = View() view.dispatch(request) request.user.can_do_things = False self.assertRaises(PermissionDenied, view.dispatch, request)
def dispatch(self, request, *args, **kwargs): if not ("supervisor_id" in request.POST or "activity" in request.FILES): return View.dispatch(self, request, *args, **kwargs) supervisor_id_value = request.POST["supervisor_id"] ': :type supervisor_id_value: str' if not (len(supervisor_id_value) == 7 and supervisor_id_value.isalnum()): return View.dispatch(self, request, *args, **kwargs) file = request.FILES["activity"] filename = file.name ': :type filename: str' filename_match = re.fullmatch(r'next_(?P<interval>\d+)\.jpg', filename) if filename_match is None or not (1 <= int( filename_match.group('interval')) <= 600000): return View.dispatch(self, request, *args, **kwargs) # TODO: Use chunks? activity_value = file.read() ': :type activity_value: bytes' activity = Snap(filename, activity_value) supervisor_id = SupervisorId(supervisor_id_value) monitoring_service.track_activity(activity, supervisor_id) return redirect('/')
def __init__(self, **kwargs): """ Sets up a context object for views to augment. Populates it with the top level articles from the DB. @todo look into RequestContext for a better method of doing this @todo look into memcache so the db isn't hit on every request """ View.__init__(self, **kwargs)
def test_setup_adds_args_kwargs_request(self): request = self.rf.get('/') args = ('arg 1', 'arg 2') kwargs = {'kwarg_1': 1, 'kwarg_2': 'year'} view = View() view.setup(request, *args, **kwargs) self.assertEqual(request, view.request) self.assertEqual(args, view.args) self.assertEqual(kwargs, view.kwargs)
def test_setup_adds_args_kwargs_request(self): request = self.rf.get("/") args = ("arg 1", "arg 2") kwargs = {"kwarg_1": 1, "kwarg_2": "year"} view = View() view.setup(request, *args, **kwargs) self.assertEqual(request, view.request) self.assertEqual(args, view.args) self.assertEqual(kwargs, view.kwargs)
def __init__(self, **kwargs): View.__init__(self, **kwargs) self.language = '' self.request = None self.params = {} self.responsejson = {} self.items = None self.item = None self.is_new = False self.has_changed = False self.format = 'JSON'
def __init__(self, **kwargs): View.__init__(self, **kwargs) # Allow this view to easily switch between feed formats. format = kwargs.get('format', self.format) try: self.feed_type = _FEED_FORMATS[format] except KeyError: raise ValueError("Unsupported feed format: {0}. Supported are: {1}".format( self.format, ', '.join(sorted(_FEED_FORMATS.iterkeys())) ))
def __init__(self, **kwargs): View.__init__(self, **kwargs) self.language = '' self.request = None self.params = {} self.responsesxml = etree.Element('REPONSES') self.responsexml = etree.SubElement(self.responsesxml, 'REPONSE') self.items = None self.item = None self.is_new = False self.has_changed = False
def __init__(self, **kwargs): View.__init__(self, **kwargs) # Allow this view to easily switch between feed formats. format = kwargs.get('format', self.format) try: self.feed_type = _FEED_FORMATS[format] except KeyError: raise ValueError( "Unsupported feed format: {0}. Supported are: {1}".format( self.format, ', '.join(sorted(_FEED_FORMATS.keys()))))
def dispatch(self, request, *args, **kwargs): # Authentication if not users.get_current_user().email() in settings.AUTHORIZED_USER: if not 'localhost' == request.META['SERVER_NAME']: if not 0 == len(settings.AUTHORIZED_USER): return HttpResponse(status=403) return View.dispatch(self, request, *args, **kwargs)
def get_urls(self): app_label = self.model._meta.app_label self.access_permission = '{app_label}.{codename}'.format( app_label=app_label, codename=self.model._meta.permissions[0][0] # First perm codename ) View = self.model.View view = View.as_view(admin=self) view = user_passes_test(lambda u: u.is_active and u.is_staff)(view) view = permission_required(self.access_permission)(view) view = login_required(view) info = app_label, View.label urlpatterns = compat.urlpatterns( url(r'^$', view, name='{}_{}'.format(*info)), url(r'^$', view, name='{}_{}_changelist'.format(*info)), ) extra_urls = self.model.View(admin=self).get_urls() if extra_urls: urlpatterns += extra_urls return urlpatterns
def setUp(self): self.fake_renderer = SEEDJSONRenderer() self.fake_response = mock.MagicMock() self.fake_view = View() self.fake_context = { 'view': self.fake_view, 'response': self.fake_response }
def dispatch(self, request, *args, **kwargs): if not self.has_permission(request, *args, **kwargs): if not request.user.is_authenticated(): path = request.get_full_path() return HttpResponseRedirect("%s?next=%s" % (settings.LOGIN_URL, path)) else: return render_to_forbidden(request) return _View.dispatch(self, request, *args, **kwargs)
def view(self, request, *args, **kwargs): """ Crear la List View del modelo """ # Class mixins = import_all_mixins() + [DeleteMixin] View = get_base_view(BaseDeleteView, mixins, self.site) # Set attributes view = View.as_view() return view(request, *args, **kwargs)
def view(self, request, *args, **kwargs): """ Crear la List View del modelo """ # Class mixins = import_all_mixins() + [DetailMixin] View = get_base_view(BaseDetailView, mixins, self.site) # Set attributes View.__bases__ = (*self.site.detail_mixins, *View.__bases__) view = View.as_view() return view(request, *args, **kwargs)
def __init__(self): self.help_message = { 'id': 'Введите ID сообщения', 'button': 'Изменить' } self.inputs_status = { 'title': '', 'description': '', 'date': '', 'select': '', } self.for_dashboard = {'title': 'Панель управления календарем'} self.ready_check_modify = False #готовность формы на изменение LoginRequiredMixin.__init__(self) View.__init__(self)
def test_post_process_urls_adds_decorator(self): fake_decorator = mock.Mock() fake_decorator.return_value = 'fake_callback' application.get_url_decorator = mock.Mock() application.get_url_decorator.return_value = fake_decorator pattern = url('^$', View.as_view(), name='index') processed_patterns = application.post_process_urls([pattern]) application.get_url_decorator.assert_called_once_with(pattern) self.assertEqual(processed_patterns[0].callback, 'fake_callback')
def view(self, request, *args, **kwargs): """ Crear la List View del modelo """ # Class mixins = import_all_mixins() + [CreateMixin] View = get_base_view(BaseCreateView, mixins, self.site) # Set attributes View.form_class = self.site.form_class View.fields = self.site.fields View.__bases__ = (*self.site.form_mixins, *View.__bases__) view = View.as_view() return view(request, *args, **kwargs)
def setUp(self): self.user = UserFactory() self.authed_view = TemplateView.as_view(template_name='base.html') self.authed_view_kwargs = {'authed': True} self.anonymous_view = TemplateView.as_view(template_name='base.html') self.anonymous_view_kwargs = {'anonymous': True} self.other_anonymous_view = View.as_view() self.view_kwargs = { 'authed_view': self.authed_view, 'authed_view_kwargs': self.authed_view_kwargs, 'anonymous_view': self.anonymous_view, 'anonymous_view_kwargs': self.anonymous_view_kwargs}
def view(self, request, *args, **kwargs): """ Crear la List View del modelo """ # Class mixins = import_all_mixins() + [ListMixin] View = get_base_view(BaseListView, mixins, self.site) # Set attriburtes View.queryset = self.site.queryset View.paginate_by = self.site.paginate_by View.__bases__ = (*self.site.list_mixins, *View.__bases__) view = View.as_view() return view(request, *args, **kwargs)
def test_apply_to_class_based_view_with_model(self): @self.registry.register(model=Model, allow_anonymous=True) def can_do_stuff(user, instance): return user.can_do_stuff and instance is not None @self.registry.require('can_do_stuff') class View(object): def dispatch(self, req, model_id, *args, **kwargs): return getattr(self, req.method.lower())(req, model_id, *args, **kwargs) def get(self, req, model_id): return model_id request = self.request_factory.get('/stuff/1') request.user = User() request.user.can_do_stuff = True view = View() view.dispatch(request, 1) request.user.can_do_stuff = False self.assertRaises(PermissionDenied, view.dispatch, request, model_id=1)
def test_post_process_urls_adds_decorator(self): def fake_callback(): pass fake_decorator = mock.Mock() fake_decorator.return_value = fake_callback self.myapp.get_url_decorator = mock.Mock() self.myapp.get_url_decorator.return_value = fake_decorator pattern = path('', View.as_view(), name='index') processed_patterns = self.myapp.post_process_urls([pattern]) self.myapp.get_url_decorator.assert_called_once_with(pattern) self.assertEqual(processed_patterns[0].callback, fake_callback)
def assert_status( code: int, user: settings.AUTH_USER_MODEL, view: View, challenge: Challenge, rf: RequestFactory, ): request = rf.get("/rand") request.challenge = challenge if user is not None: request.user = user view = view.as_view() response = view(request) assert response.status_code == code return request, response
def view(self, request, *args, **kwargs): """ Crear la List View del modelo """ # Class mixins = import_all_mixins() + [UpdateMixin] if self.site.inlines and isinstance(self.site.inlines, dict): FormsetMixin = import_mixin('FormsetMixin') class InlineMixin(FormsetMixin): formsets = self.site.inlines mixins += [InlineMixin] View = get_base_view(BaseUpdateView, mixins, self.get_site()) # Set attribures View.form_class = self.site.form_class View.fields = self.site.fields View.__bases__ = (*self.site.form_mixins, *View.__bases__) view = View.as_view() return view(request, *args, **kwargs)
def assert_status( code: int, user: settings.AUTH_USER_MODEL, view: View, challenge: Challenge, rf: RequestFactory, ): request = rf.get("/rand") request.challenge = challenge if user is not None: request.user = user view = view.as_view() if code == 403: with pytest.raises(PermissionDenied): view(request) response = None else: response = view(request) assert response.status_code == code return request, response
def view(self, request, *args, **kwargs): """Crear la List View del modelo""" # Class mixins = import_all_mixins() + [UpdateMixin] if self.site.inlines and isinstance(self.site.inlines, (list, tuple, dict)): InlinesMixin = import_mixin("InlinesMixin") class Inlines(InlinesMixin): inlines = self.site.inlines mixins += [Inlines] View = get_base_view(BaseUpdateView, mixins, self.get_site()) # Set attribures View.form_class = self.site.form_class View.fields = self.site.fields if self.site.update_mixins: View.__bases__ = (*self.site.update_mixins, *View.__bases__) else: View.__bases__ = (*self.site.form_mixins, *View.__bases__) view = View.as_view() return view(request, *args, **kwargs)
views.InstrumentDetail.as_view(), name="instrument_detail", ), path( "stations/<int:station_id>/timeseries/<int:pk>/", views.TimeseriesDetail.as_view(), name="timeseries_detail", ), path("admin/", admin.site.urls), path("api/", include(enhydris_api_urls)), # For the following, see ticket #181 path("timeseries/data/", views_old.timeseries_data, name="timeseries_data"), ] # A view that does nothing, that will be used in some fake patterns below _null_view = View.as_view() # When a user registers, an email is sent, containing a link that the user has to click # in order to confirm the email. In order to create that link, django-rest-auth uses # reverse("account_confirm_email"). So we include that in the urlpatterns, although it's # not actually being used and should not be served by Django. The web server should be # configured to route that URL to the front-end, which should then POST to the # verify-email API endpoint in order to perform the actual verification. urlpatterns += [ path("confirm-email/<str:key>/", _null_view, name="account_confirm_email") ] # When a user registers, django-allauth runs reverse("account_email_verification_sent") # in order to redirect to a page that says "We sent an email verification, click the # link in that email". In our case, registration is done by POST to an API endpoint, # which merely responds with "201". However, because something in django-allauth or in
def test_get_url_decorator_fetches_correct_perms(self, mock_permissions_required): pattern = url('^$', View.as_view(), name='index') application.get_url_decorator(pattern) mock_permissions_required.assert_called_once_with('is_staff', login_url=None)
from django.conf.urls import url from django.views.generic import View urlpatterns = [ url(r'^test_changed_urlconf/$', View.as_view(), name='test_changed_urlconf'), ]
def __init__(self, *args, **kwargs): self.queue = [] View.__init__(self, *args, **kwargs)
# -*- coding: utf-8 -*- from django.conf.urls import patterns, include, url from django.views.generic import View urlpatterns = patterns('', url(r'foo$', View.as_view(), name="foo"), )
from django.conf.urls import patterns, url from django.views.generic import View urlpatterns = patterns( '', url('', View.as_view()), )
def get_extra_urls(self): return patterns('', url(r'^login/$', View.as_view(), name='login'), )
""" URLs for filebrowser in TinyMCE """ from django.conf.urls import url from django.conf.urls import patterns from django.views.generic import View from zinnia_tinymce.views import RemoveFileView from zinnia_tinymce.views import FileBrowserView from zinnia_tinymce.views import FileBrowserCallBackView urlpatterns = patterns( '', url(r'^$', View.as_view(), name='tinymce-filebrowser-dispatch'), url(r'^callback.js$', FileBrowserCallBackView.as_view(), name='tinymce-filebrowser-callback'), url(r'^(?P<file_type>\w+)/$', FileBrowserView.as_view(), name='tinymce-filebrowser'), url(r'^(?P<file_type>\w+)/remove/(?P<pk>\d+)/$', RemoveFileView.as_view(), name='tinymce-filebrowser-remove') )
from django.conf.urls import url from django.views.generic import View urlpatterns = [ url(r"^(?P<year>\d{4})/(?P<month>\d{1,2})/$", View.as_view(), name="monthly"), url(r"^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$", View.as_view(), name="daily"), ]
from django.conf.urls import patterns, include, url from django.views.generic import View from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url("foo/$", View.as_view(), name="foo"), url(r'^', include('staff.urls')), url(r'^admin/', include(admin.site.urls)), )
def dynamic_url_pattern(cls): url_pattern = url('^test$', View.as_view(), name='test-view') url_pattern.allow_cdn = False return url_pattern
def __init__(self, **kwargs): configuration = config.load() Application.__init__(self, configuration) View.__init__(self, **kwargs)
from django.conf.urls import patterns, include, url from django.views.generic import View urlpatterns = patterns('', url(r'^test_view/$', View.as_view(), name="main"), )
def __init__(self): View.__init__(self) self.analytics_client = Client(base_url=settings.ANALYTICS_API_URL, auth_token=settings.ANALYTICS_API_KEY)
def __init__(self,prefix=None,*args,**kwargs): self.REDIRECT_TYPE = type(render_to_string(self.REDIRECT_TEMPLATE_PATH,{})) self.HTTP_RESPONSE_TYPE = type(HttpResponse()) View.__init__(self,*args,**kwargs) self.prefix = prefix self.setName(self.prefix)
"""URLs for the test app.""" from django.conf.urls.defaults import patterns, url from django.http import HttpResponse from django.views.generic import View from django_libs import views View.get = lambda req, *args, **kwargs: HttpResponse('SUCCESS!') authed_view = View.as_view() authed_view_kwargs = {'authed': True} anonymous_view = View.as_view() anonymous_view_kwargs = {'anonymous': True} urlpatterns = patterns( '', url(r'^$', views.HybridView.as_view( authed_view=authed_view, authed_view_kwargs=authed_view_kwargs, anonymous_view=anonymous_view, anonymous_view_kwargs=anonymous_view_kwargs, ), name='dummy_hybrid'), url(r'^update-session/$', views.UpdateSessionAJAXView, name='update_session'), url(r'^prototype/(?P<template_path>.*)$', views.RapidPrototypingView.as_view(), name='prototype') )
def __init__(self): View.__init__(self) self.data = {}
def dispatch(self, request, *args, **kwargs): return View.dispatch(self, request, *args, **kwargs)
from django.conf.urls import patterns, url from django.views.generic import View urlpatterns = patterns( '', url(r'^simple/action/$', View.as_view(), name='simpleAction'), )
def static_url_pattern(cls): return url('^test$', View.as_view(), name='test-view')
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() from django.views.generic import View urlpatterns = patterns('', url(r'^$', View.as_view(), name='sitemap'), # url(r'^example/', include('example.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)), )
from django.conf.urls import patterns, url from django.views.generic import View urlpatterns = patterns('', url(r'^(?P<pk>[\w\d]+)/module/$', View.as_view(), name='module') )
def __init__(self, **kwargs): View.__init__(self, **kwargs) self.form = None self.form_values = None self.term = None