Python django.conf.urls.url() Examples

The following are code examples for showing how to use django.conf.urls.url(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 7 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example 2
Project: xadmin_bugfix   Author: vip68   File: sites.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example 3
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example 4
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example 5
Project: django-dynamic-views   Author: ddaan   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def order_by(self):
        """
        Propery method to determine the order by.
        First check if it is used in the url, then retrieve the user setting and else it is an empty string

        :return: string order by
        """
        order_by = self.request.GET.get('order_by', None)
        if order_by in self.get_field_names():
            if order_by in self.get_order_fields():
                if self.request.GET.get('sort') == 'DESC':
                    return '-%s' % order_by
                else:
                    return order_by

        return '' 
Example 6
Project: django-dynamic-views   Author: ddaan   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def urls(self):
        urls = []
        for link in self.links:
            if hasattr(self, '{}_link'.format(link)):
                link_name = getattr(self, '{}_link'.format(link))
            else:
                link_name = link

            url_check = r'{}/{}/'.format(self.model_name, link_name)

            if hasattr(self, '{}_kwargs'.format(link)):
                link_kwargs = getattr(self, '{}_kwargs_regexp'.format(link))
                url_check += '{}/'.format(link_kwargs)

            # Add start and end of line to regex pattern
            url_check = '^%s$' % url_check

            action_cls = getattr(self, '{}_class'.format(link))
            urls.append(url(url_check, action_cls, name=self.link_name(link)))

        return urls 
Example 7
Project: omni-forms   Author: omni-digital   File: wagtail_hooks.py    MIT License 6 votes vote down vote up
def add_field_button(self, pk, classnames_add=None, classnames_exclude=None):
        """
        Helper method for generating a button to display in the list view
        for the WagtailOmniForm ModelAdmin class. The button itself will
        be displayed in each row, next to the  edit and delete buttons

        :param pk: The primary key of the OmniForm model instance
        :param classnames_add: List of extra class names to add to the button
        :param classnames_exclude: List class names to remove from the button
        :return: Dict of data required to construct a button in the template
        """
        if classnames_add is None:
            classnames_add = []
        if classnames_exclude is None:
            classnames_exclude = []

        classnames = self.edit_button_classnames + classnames_add
        classname = self.finalise_classname(classnames, classnames_exclude)
        return {
            'url': self.url_helper.get_action_url('select_field', pk),
            'label': 'Add field',
            'classname': classname,
            'title': 'Add a new field',
        } 
Example 8
Project: omni-forms   Author: omni-digital   File: wagtail_hooks.py    MIT License 6 votes vote down vote up
def add_handler_button(self, pk, classnames_add=None, classnames_exclude=None):
        """
        Helper method for generating a button to display in the list view
        for the WagtailOmniForm ModelAdmin class. The button itself will
        be displayed in each row, next to the edit and delete buttons

        :param pk: The primary key of the OmniForm model instance
        :param classnames_add: List of extra class names to add to the button
        :param classnames_exclude: List class names to remove from the button
        :return: Dict of data required to construct a button in the template
        """
        if classnames_add is None:
            classnames_add = []
        if classnames_exclude is None:
            classnames_exclude = []

        classnames = self.edit_button_classnames + classnames_add
        classname = self.finalise_classname(classnames, classnames_exclude)
        return {
            'url': self.url_helper.get_action_url('select_handler', pk),
            'label': 'Add handler',
            'classname': classname,
            'title': 'Add a new handler',
        } 
Example 9
Project: omni-forms   Author: omni-digital   File: wagtail_hooks.py    MIT License 6 votes vote down vote up
def clone_form_button(self, pk, classnames_add=None, classnames_exclude=None):
        """
        Helper method for generating a button to display in the list view
        for the WagtailOmniForm ModelAdmin class. The button itself will
        be displayed in each row, next to the  edit and delete buttons

        :param pk: The primary key of the OmniForm model instance
        :param classnames_add: List of extra class names to add to the button
        :param classnames_exclude: List class names to remove from the button
        :return: Dict of data required to construct a button in the template
        """
        if classnames_add is None:
            classnames_add = []
        if classnames_exclude is None:
            classnames_exclude = []

        classnames = self.edit_button_classnames + classnames_add
        classname = self.finalise_classname(classnames, classnames_exclude)
        return {
            'url': self.url_helper.get_action_url('clone_form', pk),
            'label': 'Clone form',
            'classname': classname,
            'title': 'Clone form',
        } 
Example 10
Project: django-performance-testing   Author: PaesslerAG   File: test_integrates_with_django_test_client.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_can_specify_limits_through_settings_for_django_test_client(
        db, settings, client, method, limit, value, cfg_key, items_name,
        view_ctx):
    settings.PERFORMANCE_LIMITS = {
        'django.test.client.Client': {
            cfg_key: {
                'total': limit
            }
        }
    }
    with view_ctx(value=value) as vctx:
        with pytest.raises(LimitViolationError) as excinfo:
            vctx.request(getattr(client, method.lower()))
        assert excinfo.value.context == {
            'Client.request': ['{method} {url}'.format(
                url=vctx.url, method=method)]}
        assert excinfo.value.items_name == items_name, \
            excinfo.value.base_error_msg 
Example 11
Project: django-glitter   Author: developersociety   File: admin.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_fieldsets(self, request, obj=None):
        fields = [
            'url', 'title', 'parent', 'tags', 'login_required', 'show_in_navigation',
        ]

        # Don't show login_required unless needed
        if not getattr(settings, 'GLITTER_SHOW_LOGIN_REQUIRED', False):
            fields.remove('login_required')

        # Show glitter tags if it's set to show.
        if not getattr(settings, 'GLITTER_PAGES_TAGS', False):
            fields.remove('tags')

        fieldsets = [
            [None, {'fields': fields}],

            ['Advanced options', {
                'classes': ['collapse'],
                'fields': ['glitter_app_name'],
            }]
        ]
        return fieldsets 
Example 12
Project: chattR   Author: patrickstocklin   File: sites.py    GNU General Public License v2.0 6 votes vote down vote up
def password_change(self, request, extra_context=None):
        """
        Handles the "change password" task -- both form display and validation.
        """
        from django.contrib.admin.forms import AdminPasswordChangeForm
        from django.contrib.auth.views import password_change
        url = reverse('admin:password_change_done', current_app=self.name)
        defaults = {
            'current_app': self.name,
            'password_change_form': AdminPasswordChangeForm,
            'post_change_redirect': url,
            'extra_context': dict(self.each_context(request), **(extra_context or {})),
        }
        if self.password_change_template is not None:
            defaults['template_name'] = self.password_change_template
        return password_change(request, **defaults) 
Example 13
Project: chattR   Author: patrickstocklin   File: options.py    GNU General Public License v2.0 6 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = [
            url(r'^$', wrap(self.changelist_view), name='%s_%s_changelist' % info),
            url(r'^add/$', wrap(self.add_view), name='%s_%s_add' % info),
            url(r'^(.+)/history/$', wrap(self.history_view), name='%s_%s_history' % info),
            url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_%s_delete' % info),
            url(r'^(.+)/$', wrap(self.change_view), name='%s_%s_change' % info),
        ]
        return urlpatterns 
Example 14
Project: django-admin-reset   Author: tiborhari   File: admin.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def password_reset_url(self, request, id, form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = self.get_object(request, unquote(id))
        if user is None:
            raise Http404(_('%(name)s object with primary key %(key)r does '
                            'not exist.') % {
                'name': self.model._meta.verbose_name,
                'key': escape(id),
            })

        token_generator = PasswordResetTokenGenerator()
        url = reverse(
            'admin:password_reset_confirm',
            kwargs={'uidb64': force_text(
                urlsafe_base64_encode(force_bytes(user.pk))),
                'token': token_generator.make_token(user)})
        url = request.build_absolute_uri(url)
        return TemplateResponse(
            request,
            'admin/password_reset_url.html',
            context={'user': user, 'url': url, 'title': _('Password reset'),
                     'timeout_days': settings.PASSWORD_RESET_TIMEOUT_DAYS}) 
Example 15
Project: opadmin   Author: cc0411   File: sites.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example 16
Project: StormOnline   Author: stormsha   File: sites.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example 17
Project: heltour   Author: cyanfish   File: admin.py    MIT License 6 votes vote down vote up
def link_reminder(self, request, queryset):
        slack_users = slackapi.get_user_list()
        by_email = {u.email: u.id for u in slack_users}

        for sp in queryset.filter(is_active=True, player__slack_user_id='').select_related(
            'player').nocache():
            uid = by_email.get(sp.player.email)
            if uid:
                token = LoginToken.objects.create(slack_user_id=uid,
                                                  username_hint=sp.player.lichess_username,
                                                  expires=timezone.now() + timedelta(days=30))
                url = reverse('by_league:login_with_token',
                              args=[sp.season.league.tag, token.secret_token])
                url = request.build_absolute_uri(url)
                text = 'Reminder: You need to link your Slack and Lichess accounts. <%s|Click here> to do that now. Contact a mod if you need help.' % url
                slackapi.send_message(uid, text)

        return redirect('admin:tournament_seasonplayer_changelist') 
Example 18
Project: pyaedj   Author: google   File: extensions.py    Apache License 2.0 6 votes vote down vote up
def _get_cancel_url(self, request, object_id):
    """Creates an appropriate cancel URL: to list view or to obejct view."""
    if self._use_query_string_view_routing():
      # current path: /cms/{{ model }}-{{ pk }}/change/?cms-action{{ action }}
      if object_id is None:
        url = request.path + '../'
      else:
        url = request.path
      return HttpResponseRedirect(url)
    else:
      # current path: /cms/{{ model }}-{{ pk }}/{{ action }}/
      if object_id is None:
        url = request.path + '../'
      else:
        url = request.path + '../%s/' % self._ACTION_CHANGE_NAME
      return HttpResponseRedirect(url) 
Example 19
Project: AneMo   Author: jspargo   File: options.py    GNU General Public License v2.0 6 votes vote down vote up
def get_urls(self):
        from django.conf.urls import patterns, url

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = patterns('',
            url(r'^$', wrap(self.changelist_view), name='%s_%s_changelist' % info),
            url(r'^add/$', wrap(self.add_view), name='%s_%s_add' % info),
            url(r'^(.+)/history/$', wrap(self.history_view), name='%s_%s_history' % info),
            url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_%s_delete' % info),
            url(r'^(.+)/$', wrap(self.change_view), name='%s_%s_change' % info),
        )
        return urlpatterns 
Example 20
Project: xadmin_bugfix   Author: vip68   File: sites.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 21
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 22
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 23
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 24
Project: django-dynamic-views   Author: ddaan   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_paginate_url(self):
        """
        The url it should paginate on. By default an empty string

        :return: string url
        """
        return '' 
Example 25
Project: omni-forms   Author: omni-digital   File: wagtail_hooks.py    MIT License 5 votes vote down vote up
def _get_object_specific_action_url_pattern(self, action):
        """
        Allows us to hook extra urls into the model admin

        :param action: View action to get the url pattern for
        :return:
        """
        if action == 'clone_form':
            return r'^{0}/{1}/{2}/(?P<instance_pk>[-\w]+)/$'.format(
                self.opts.app_label,
                self.opts.model_name,
                action
            )
        elif action == 'add_field':
            return r'^{0}/{1}/{2}/(?P<instance_pk>[-\w]+)/(?P<related_object_ctype_id>[\d]+)/$'.format(
                self.opts.app_label,
                self.opts.model_name,
                action
            )
        elif action in ('change_field', 'delete_field'):
            return r'^{0}/{1}/{2}/(?P<instance_pk>[-\w]+)/(?P<related_object_id>[\d]+)/$'.format(
                self.opts.app_label,
                self.opts.model_name,
                action
            )
        elif action == 'add_handler':
            return r'^{0}/{1}/{2}/(?P<instance_pk>[-\w]+)/(?P<related_object_ctype_id>[\d]+)/$'.format(
                self.opts.app_label,
                self.opts.model_name,
                action
            )
        elif action in ('change_handler', 'delete_handler'):
            return r'^{0}/{1}/{2}/(?P<instance_pk>[-\w]+)/(?P<related_object_id>[\d]+)/$'.format(
                self.opts.app_label,
                self.opts.model_name,
                action
            )
        return super(WagtailOmniFormURLHelper, self)._get_object_specific_action_url_pattern(action) 
Example 26
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def setUp(self):
        self.url_patterns = patterns(
            '',
            url(r'a-view/$', MockApiView.as_view(), name='a test view'),
            url(r'b-view$', MockApiView.as_view(), name='a test view'),
            url(r'c-view/$', MockApiView.as_view(), name='a test view'),
            url(r'a-view/child/?$', MockApiView.as_view()),
            url(r'a-view/child2/?$', MockApiView.as_view()),
            url(r'another-view/?$', MockApiView.as_view(),
                name='another test view'),
            url(r'view-with-param/(:?<ID>\d+)/?$', MockApiView.as_view(),
                name='another test view'),
            url(r'a-view-honky/?$', MockApiView.as_view(), name='a test view'),
        )
        self.urlparser = UrlParser() 
Example 27
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def test_format_api_patterns_url_import(self):
        urls = patterns('', url(r'api/base/path/', include(self.url_patterns)))
        apis = self.urlparser.get_apis(urls)

        self.assertEqual(len(self.url_patterns), len(apis)) 
Example 28
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def test_format_api_patterns_excluded_namesapce(self):
        urls = patterns(
            '',
            url(r'api/base/path/',
                include(self.url_patterns, namespace='exclude'))
        )
        apis = self.urlparser.format_api_patterns(
            url_patterns=urls, exclude_namespaces='exclude')

        self.assertEqual([], apis) 
Example 29
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def test_format_api_patterns_url_import_with_routers(self):

        class MockApiViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            model = User
            queryset = User.objects.all()

        class AnotherMockApiViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            model = User
            queryset = User.objects.all()

        router = DefaultRouter()
        router.register(r'other_views', MockApiViewSet, base_name='test_base_name')
        router.register(r'more_views', AnotherMockApiViewSet, base_name='test_base_name')

        urls_app = patterns('', url(r'^', include(router.urls)))
        urls = patterns(
            '',
            url(r'api/', include(urls_app)),
            url(r'test/', include(urls_app))
        )
        apis = self.urlparser.get_apis(urls)

        self.assertEqual(
            4, sum(api['path'].find('api') != -1 for api in apis))
        self.assertEqual(
            4, sum(api['path'].find('test') != -1 for api in apis)) 
Example 30
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def test_get_api_callback_not_rest_view(self):
        non_api = patterns(
            '',
            url(r'something', NonApiView.as_view())
        )
        callback = self.urlparser.filter_api_view_callbacks(non_api[0])

        self.assertIsNone(callback) 
Example 31
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def setUp(self):
        class FuzzyApiView(APIView):
            def get(self, request):
                pass

        class ShinyApiView(APIView):
            def get(self, request):
                pass

        api_fuzzy_url_patterns = patterns(
            '', url(r'^item/$', FuzzyApiView.as_view(), name='find_me'))
        api_shiny_url_patterns = patterns(
            '', url(r'^item/$', ShinyApiView.as_view(), name='hide_me'))

        fuzzy_app_urls = patterns(
            '', url(r'^api/', include(api_fuzzy_url_patterns,
                                      namespace='api_fuzzy_app')))
        shiny_app_urls = patterns(
            '', url(r'^api/', include(api_shiny_url_patterns,
                                      namespace='api_shiny_app')))

        self.project_urls = patterns(
            '',
            url('my_fuzzy_app/', include(fuzzy_app_urls)),
            url('my_shiny_app/', include(shiny_app_urls)),
        ) 
Example 32
Project: django-performance-testing   Author: PaesslerAG   File: test_integrates_with_django_test_client.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __enter__(self):
        urlpatterns.append(url(self.reverse_name, self, {}, self.reverse_name))
        return self 
Example 33
Project: django-performance-testing   Author: PaesslerAG   File: test_integrates_with_django_test_client.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def url(self):
        return reverse(self.reverse_name) 
Example 34
Project: django-performance-testing   Author: PaesslerAG   File: test_integrates_with_django_test_client.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def request(self, method):
        response = method(self.url)
        print(response.status_code)  # helps when it fails
        return response 
Example 35
Project: wagtailcloudinary   Author: dteskera   File: sites.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url
        urlpatterns = [
            url(r'^browse/$', staff_nocache(self.browse), name="browse"),
            url(r'^select/(.*)$', staff_nocache(self.select), name="select"),
            url(r'^update/(.*)$', staff_nocache(self.update), name="update"),
            url(r'^upload/$', staff_nocache(self.upload), name="upload"),
        ]
        return urlpatterns 
Example 36
Project: wagtailcloudinary   Author: dteskera   File: sites.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def select(self, request, path):
        slugs = path.split('/')
        slugs.insert(2, self.admin_image_version)
        transformed = '/'.join(slugs)
        return render_modal_workflow(
            request,
            None,
            'wagtailcloudinary/image_chosen.js',
            {
                'image_json': {
                    'value': path,
                    'url': '{}{}'.format(self.base_url, transformed)
                }
            }
        ) 
Example 37
Project: django-glitter   Author: developersociety   File: admin.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_urls(self):
        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)
        urlpatterns = super().get_urls()

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = [
            url(r'^$', wrap(self.grid_view)),
            url(r'^tree/$', wrap(self.changelist_view), name='%s_%s_tree' % info),
            url(r'^(\d+)/duplicate/$', wrap(self.duplicate_page), name='%s_%s_duplicate' % info),
        ] + urlpatterns
        return urlpatterns 
Example 38
Project: chattR   Author: patrickstocklin   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def media(self):
        extra = '' if settings.DEBUG else '.min'
        js = [
            'core.js',
            'admin/RelatedObjectLookups.js',
            'jquery%s.js' % extra,
            'jquery.init.js'
        ]
        if self.actions is not None:
            js.append('actions%s.js' % extra)
        if self.prepopulated_fields:
            js.extend(['urlify.js', 'prepopulate%s.js' % extra])
        return forms.Media(js=[static('admin/js/%s' % url) for url in js]) 
Example 39
Project: normandy   Author: mozilla   File: routers.py    Mozilla Public License 2.0 5 votes vote down vote up
def register_view(self, prefix, View, *, name, allow_cdn=True, **kwargs):
        url_pattern = url(r"^{}/$".format(prefix), View.as_view(), name=name, **kwargs)
        url_pattern.allow_cdn = allow_cdn
        self.registered_view_urls.append(url_pattern) 
Example 40
Project: normandy   Author: mozilla   File: test_api.py    Mozilla Public License 2.0 5 votes vote down vote up
def static_url_pattern_conf(cls, mock_conf, dummy_view):
        mock_conf.urlpatterns = [url("^test$", dummy_view, name="test-view")]
        return mock_conf 
Example 41
Project: normandy   Author: mozilla   File: test_api.py    Mozilla Public License 2.0 5 votes vote down vote up
def dynamic_url_pattern_conf(cls, mock_conf, dummy_view):
        url_pattern = url("^test$", dummy_view, name="test-view")
        url_pattern.allow_cdn = False
        mock_conf.urlpatterns = [url_pattern]
        return mock_conf 
Example 42
Project: ramlwrap   Author: jmons   File: raml.py    MIT License 5 votes vote down vote up
def raml_url_patterns(raml_filepath, function_map):
    """
    creates url patterns that match the endpoints in the raml file, so can be quickly inserted into django urls.
    Note these
    :param raml_filepath: the path to the raml file (not a file pointer)
    :param function_map: a dictionary of urls to functions for mapping
    :return:
    """

    # This function will run in three phases:
    # 1) Load the raml (as a yaml document)
    # 2) Parse the raml into nodes that represent 'endpoints'
    # 3) Convert endpoints into a url structure

    # migrating from pyraml: file handling now has to be done by us
    # worry about streaming files in future version (for VERY BIG raml?)
    f = open(raml_filepath)
    tree = yaml.load(f, Loader=Loader)  # This loader has the !include directive
    f.close()

    # The resource map is the found nodes

    patterns = []
    to_look_at = [
        {
            "node": tree,
            "path": ""
        }
    ]

    # FIXME: get baseuri, and default media types out here

    defaults = {
        "content_type": "application/json",
    }

    for item in to_look_at:
        _parse_child(item, patterns, to_look_at, function_map, defaults)

    return patterns 
Example 43
Project: tg-apicore   Author: thorgate   File: views.py    ISC License 5 votes vote down vote up
def get_site_url(self) -> str:
        """ Should return your site's url without path, e.g. https://example.com/ """
        raise NotImplementedError() 
Example 44
Project: tg-apicore   Author: thorgate   File: views.py    ISC License 5 votes vote down vote up
def urlpatterns(cls):
        return [
            # This one is for when the version is valid
            url(r'^(?P<version>(\d{4}-\d{2}-\d{2}))/', cls.as_view()),
            # This one is catch-all for everything else, including invalid versions
            url(r'^', cls.as_view()),
        ] 
Example 45
Project: django-admin-reset   Author: tiborhari   File: admin.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_urls(self):
        return [
            url('^(?P<id>[^/.]+)/password_reset_url/$',
                self.admin_site.admin_view(self.password_reset_url),
                name='password_reset_url'),
            url(r'^password_reset_confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/'
                r'(?P<token>[0-9A-Za-z]+-[0-9A-Za-z]+)/$',
                PasswordResetConfirmView.as_view(
                    success_url=reverse_lazy('admin:password_reset_complete')),
                name='password_reset_confirm'),
            url(r'^password_reset_complete/done/$',
                AdminResetCompleteView.as_view(),
                name='password_reset_complete')
        ] + super(PasswordResetUserAdmin, self).get_urls() 
Example 46
Project: opadmin   Author: cc0411   File: sites.py    GNU General Public License v3.0 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 47
Project: wagtailplus   Author: MechanisM   File: utils.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_component_urls():
    """
    Returns list of address component URLs based on address attribute map.

    :rtype: list.
    """
    component_patterns = []
    
    for component, label in ADDRESS_ATTR_MAP.iteritems():
        label           = unicode(label)
        chooser_name    = 'wagtailaddresses_{0}_chooser'.format(component)
        create_name     = 'wagtailaddresses_{0}_create'.format(component)
        
        component_patterns.append(url(
            r'^{0}-chooser/$'.format(label.lower().replace(' ', '-')),
            choosers.ChooseComponentView.as_view(
                comp_type=label,
                chooser_name=chooser_name,
                create_name=create_name
            ),
            name=chooser_name
        ))
        
        component_patterns.append(url(
            r'^{0}-chooser/create/$'.format(label.lower().replace(' ', '-')),
            choosers.CreateComponentView.as_view(
                comp_type=label,
                chooser_name=chooser_name,
                create_name=create_name
            ),
            name=create_name
        ))

    return component_patterns 
Example 48
Project: StormOnline   Author: stormsha   File: sites.py    Apache License 2.0 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 49
Project: litmus-site   Author: alps-jbnu   File: submission.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_urls(self):
        return [url(r'^(\d+)/judge/$', self.judge_view, name='judge_submission_rejudge')] + \
               super(SubmissionAdmin, self).get_urls() 
Example 50
Project: litmus-site   Author: alps-jbnu   File: contest.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_urls(self):
        return [url(r'^rate/all/$', self.rate_all_view, name='judge_contest_rate_all'),
                url(r'^(\d+)/rate/$', self.rate_view, name='judge_contest_rate')] + super(ContestAdmin, self).get_urls()