コード例 #1
0
    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)
コード例 #2
0
    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('/')
コード例 #3
0
ファイル: base.py プロジェクト: rjlowes/codejockey
    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)
コード例 #4
0
    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)
コード例 #5
0
ファイル: test_base.py プロジェクト: thibaudcolas/django
    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)
コード例 #6
0
 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'
コード例 #7
0
ファイル: xferbasic.py プロジェクト: Lucterios2/core
 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'
コード例 #8
0
ファイル: feeds.py プロジェクト: nschlemm/django-fluent-blogs
    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()))
            ))
コード例 #9
0
ファイル: xferbasic.py プロジェクト: povtux/core
 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
コード例 #10
0
    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()))))
コード例 #11
0
ファイル: views.py プロジェクト: grapswiz/awikie
 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)
コード例 #12
0
    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
コード例 #13
0
 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
     }
コード例 #14
0
ファイル: views.py プロジェクト: Shirk/OpenSlides
 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)
コード例 #15
0
ファイル: views.py プロジェクト: Shirk/OpenSlides
 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)
コード例 #16
0
    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)
コード例 #17
0
ファイル: detail.py プロジェクト: dbsiavichay/django-hydra
    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)
コード例 #18
0
ファイル: views.py プロジェクト: KrupinSA/prj_test
    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)
コード例 #19
0
    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')
コード例 #20
0
ファイル: create.py プロジェクト: dbsiavichay/django-hydra
    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)
コード例 #21
0
    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}
コード例 #22
0
ファイル: list.py プロジェクト: dbsiavichay/django-hydra
    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)
コード例 #23
0
    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)
コード例 #24
0
    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)
コード例 #25
0
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
コード例 #26
0
    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)
コード例 #27
0
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
コード例 #28
0
ファイル: utils.py プロジェクト: comic/comic-django
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
コード例 #29
0
    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)
コード例 #30
0
ファイル: urls.py プロジェクト: openmeteo/enhydris
        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
コード例 #31
0
 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)
コード例 #32
0
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'),
]
コード例 #33
0
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'),
]
コード例 #34
0
ファイル: views.py プロジェクト: Pike/l12y-render
 def __init__(self, *args, **kwargs):
     self.queue = []
     View.__init__(self, *args, **kwargs)
コード例 #35
0
ファイル: urls.py プロジェクト: Automatique/django-sites
# -*- 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"),
)
コード例 #36
0
from django.conf.urls import patterns, url
from django.views.generic import View

urlpatterns = patterns(
    '',
    url('', View.as_view()),
)
コード例 #37
0
ファイル: test_base.py プロジェクト: pculture/django-djam
 def get_extra_urls(self):
     return patterns('',
         url(r'^login/$',
             View.as_view(),
             name='login'),
     )
コード例 #38
0
"""
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')
)
コード例 #39
0
ファイル: urls.py プロジェクト: pinax/pinax-calendars
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"),
]
コード例 #40
0
ファイル: urls.py プロジェクト: pombredanne/django-listable
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)),
)
コード例 #41
0
ファイル: test_api.py プロジェクト: andymikulski/normandy
 def dynamic_url_pattern(cls):
     url_pattern = url('^test$', View.as_view(), name='test-view')
     url_pattern.allow_cdn = False
     return url_pattern
コード例 #42
0
ファイル: views.py プロジェクト: kyokenn/djradicale
 def __init__(self, **kwargs):
     configuration = config.load()
     Application.__init__(self, configuration)
     View.__init__(self, **kwargs)
コード例 #43
0
ファイル: urls.py プロジェクト: pablorecio/contentious
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"),
)
コード例 #44
0
 def __init__(self):
     View.__init__(self)
     self.analytics_client = Client(base_url=settings.ANALYTICS_API_URL,
                                    auth_token=settings.ANALYTICS_API_KEY)
コード例 #45
0
 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)
コード例 #46
0
ファイル: urls.py プロジェクト: pombredanne/django-libs
"""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')
)
コード例 #47
0
ファイル: JsonRequest.py プロジェクト: msreis/SigNetSim
	def __init__(self):
		View.__init__(self)
		self.data = {}
コード例 #48
0
 def dispatch(self, request, *args, **kwargs):
     return View.dispatch(self, request, *args, **kwargs)
コード例 #49
0
ファイル: views.py プロジェクト: cmscom/edx-platform
 def __init__(self):
     View.__init__(self)
     self.analytics_client = Client(base_url=settings.ANALYTICS_API_URL, auth_token=settings.ANALYTICS_API_KEY)
コード例 #50
0
ファイル: views.py プロジェクト: OpenLuna/luna-chatterbot
 def dispatch(self, request, *args, **kwargs):
     return View.dispatch(self, request, *args, **kwargs)
コード例 #51
0
ファイル: urls.py プロジェクト: Anirudh58/django-mini-project
from django.conf.urls import patterns, url
from django.views.generic import View


urlpatterns = patterns(
    '',
    url(r'^simple/action/$', View.as_view(), name='simpleAction'),
)
コード例 #52
0
ファイル: test_api.py プロジェクト: andymikulski/normandy
 def static_url_pattern(cls):
     return url('^test$', View.as_view(), name='test-view')
コード例 #53
0
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)),
)
コード例 #54
0
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')
)
コード例 #55
0
 def __init__(self, **kwargs):
     View.__init__(self, **kwargs)
     self.form = None
     self.form_values = None
     self.term = None