我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.urls.include()。
def get_urlpatterns(handler_module): # NB: This could just as well be your `urls.py` – it's here to make testing various handler # configurations easier. router = Router.from_file(os.path.join(os.path.dirname(__file__), 'tests', 'petstore-expanded.yaml')) router.add_handlers(handler_module) validate_router(router) router_urls = router.get_urls( decorate=(csrf_exempt,), optional_trailing_slash=True, ) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include(router_urls, 'api')), url(r'^api/', include(get_docs_urls(router, 'api-docs'), 'api-docs')), ] return urlpatterns
def include_docs_urls( title=None, description=None, schema_url=None, public=True, patterns=None, generator_class=SchemaGenerator): docs_view = get_docs_view( title=title, description=description, schema_url=schema_url, public=public, patterns=patterns, generator_class=generator_class, ) schema_js_view = get_schemajs_view( title=title, description=description, schema_url=schema_url, public=public, patterns=patterns, generator_class=generator_class, ) urls = [ url(r'^$', docs_view, name='docs-index'), url(r'^schema.js$', schema_js_view, name='schema-js') ] return include(urls, namespace='api-docs')
def test_partner_patterns_instance_ns(partner_factory): partner = partner_factory(slug='automatic_partner', auto_set_partner=False) set_partner(partner) urlconf = (partner_patterns( url(r'^ns/', include(base_urlconf, namespace='instance-ns')) ),) url_ = reverse('instance-ns:static-url', urlconf) assert url_ == '/automatic_partner/ns/static/' url_ = reverse('instance-ns:static-url', urlconf, kwargs=dict( partner_slug='manual_partner')) assert url_ == '/manual_partner/ns/static/' url_ = reverse('instance-ns:dynamic-url', urlconf, kwargs=dict(pk=1)) assert url_ == '/automatic_partner/ns/dynamic/1/' url_ = reverse('instance-ns:dynamic-url', urlconf, kwargs=dict( partner_slug='manual_partner', pk=1)) assert url_ == '/manual_partner/ns/dynamic/1/' url_ = reverse('instance-ns:dynamic-url', urlconf, args=(1,)) assert url_ == '/automatic_partner/ns/dynamic/1/'
def test_register_adds_default_routes_from_modelname(self): class ParentView(ModelView): pass class FooView(ParentView): model = FooModel class BarView(ParentView): model = BarModel r = Router() r.register(ParentView) urls_module.urlpatterns = [url(r'^', include(r.urls))] self.assertTrue(is_valid_path('/foo_model/', urls_module)) self.assertTrue(is_valid_path('/foo_model/1/', urls_module)) self.assertTrue(is_valid_path('/bar_model/12345/', urls_module)) self.assertFalse(is_valid_path('/bar_model/lalala/', urls_module)) self.assertFalse(is_valid_path('/another_model/', urls_module))
def test_register_adds_custom_route_names(self): class ParentView(ModelView): pass class FooView(ParentView): model = FooModel route = 'foo' class BarView(ParentView): model = BarModel # Explicit Route objects should also be accepted route = Route('bar') r = Router() r.register(ParentView) urls_module.urlpatterns = [url(r'^', include(r.urls))] self.assertTrue(is_valid_path('/foo/', urls_module)) self.assertTrue(is_valid_path('/foo/1/', urls_module)) self.assertTrue(is_valid_path('/bar/12345/', urls_module)) # Default named routes should not be there self.assertFalse(is_valid_path('/foo_model/1/', urls_module)) self.assertFalse(is_valid_path('/bar_model/1/', urls_module))
def test_register_obeys_custom_route_config(self): class ParentView(ModelView): pass class FooView(ParentView): model = FooModel route = Route('foo', list_endpoint=False) class BarView(ParentView): model = BarModel route = Route('bar', detail_endpoint=False) r = Router() r.register(ParentView) urls_module.urlpatterns = [url(r'^', include(r.urls))] self.assertFalse(is_valid_path('/foo/', urls_module)) self.assertTrue(is_valid_path('/foo/1/', urls_module)) self.assertTrue(is_valid_path('/bar/', urls_module)) self.assertFalse(is_valid_path('/bar/1/', urls_module))
def test_app_creation(self): app_name = 'TestUssdApp' call_command('create_ussd_app', app_name) ussd_url = [ url(r'^ussd/', include('TestUssdApp.urls')) ] urls.urlpatterns += ussd_url end_point_url = "http://localhost:8081/ussd/TestUssdApp_ussd_gateway" payload = { "phoneNumber": "0717199135", "sessionId": "12", "text": "1", "language": "en", "serviceCode": "200"} response = self.client.post(end_point_url, data=json.dumps(payload), content_type="application/json",) self.assertEqual(response.content, b'END Example Quit Screen. Delete this and define your own customer journey screens.') self.assertEqual(response.status_code, 200) print(response.status_code) os.system('rm -r TestUssdApp') # Remove created app. Clean up
def get_patterns(self): self.discover_plugins() # We want untranslated name of the plugin for its slug so we deactivate translation lang = get_language() deactivate_all() try: url_patterns = [] for plugin in self.get_all_plugins(): p = plugin() slug = slugify(force_text(normalize_name(p.__class__.__name__))) url_patterns += [ url(r'^plugin/%s/' % (slug,), include(p.plugin_urls)), ] finally: # Reactivate translation activate(lang) return url_patterns
def get_plugin_urls(): urlpatterns = [] for plugin in list(registry.get_plugins().values()): slug = getattr(plugin, 'slug', None) if slug: article_urlpatterns = plugin.urlpatterns.get('article', []) urlpatterns += [ url(r'^(?P<article_id>\d+)/plugin/' + slug + '/', include(article_urlpatterns)), url(r'^(?P<path>.+/|)_plugin/' + slug + '/', include(article_urlpatterns)), ] root_urlpatterns = plugin.urlpatterns.get('root', []) urlpatterns += [ url(r'^_plugin/' + slug + '/', include(root_urlpatterns)), ] return urlpatterns
def urls(self): """ Provides URLconf details for the ``Api`` and all registered ``Resources`` beneath it. """ pattern_list = [ url(r"^(?P<api_name>%s)%s$" % (self.api_name, trailing_slash()), self.wrap_view('top_level'), name="api_%s_top_level" % self.api_name), ] for name in sorted(self._registry.keys()): self._registry[name].api_name = self.api_name pattern_list.append((r"^(?P<api_name>%s)/" % self.api_name, include(self._registry[name].urls))) urlpatterns = self.prepend_urls() overridden_urls = self.override_urls() if overridden_urls: warnings.warn("'override_urls' is a deprecated method & will be removed by v1.0.0. Please rename your method to ``prepend_urls``.") urlpatterns += overridden_urls urlpatterns += patterns('', *pattern_list ) return urlpatterns
def default_urlpatterns(provider): package = provider.get_package() login_view = import_attribute(package + '.views.login') callback_view = import_attribute(package + '.views.callback') logout_view = import_attribute(package + '.views.logout') urlpatterns = [ url('^login/$', login_view, name=provider.id + '_login'), url('^login/callback/$', callback_view, name=provider.id + '_callback'), url('^logout/$', logout_view, name=provider.id + '_logout'), ] return [url('^' + provider.get_slug() + '/', include(urlpatterns))]
def construct_endpoint(self, instance, spec, loc, context): """ Constructor of '.endpoint' predicate. It gets the generated views and it maps them with urlpatterns which will later be used from django. """ parent_name = context.get('parent_name') collections = self.get_structural_elements(instance) if not collections: raise utils.DRFAdapterException( '.endpoint without any collection found.', loc=loc) router = routers.DefaultRouter() for collection in collections: collection_spec = instance.get(collection) view = collection_spec.get(self.ADAPTER_CONF) basename = parent_name + '_' + collection router.register(collection, view, base_name=basename) self.urls[parent_name] = url( r'^' + parent_name + '/', include(router.urls))
def get_urls(self): """ Override the default get_urls() method to move default Oscar promotions from location r'' to r'^promotions/' to free up space for Wagtail's wagtailcore serving mechanism. """ urls = super(OscarApplication, self).get_urls()[:-1] urls.append(url(r'^promotions/', include(self.promotions_app.urls)),) return urls
def _decorated_urls(self): urlpatterns = self._get_default_urlpatterns() # Apply access controls to all views in the patterns permissions = getattr(self, 'permissions', []) _decorate_urlconf(urlpatterns, require_perms, permissions) _decorate_urlconf(urlpatterns, _current_component, panel=self) # Return the three arguments to django.conf.urls.include return urlpatterns, self.slug, self.slug
def _decorated_urls(self): urlpatterns = self._get_default_urlpatterns() default_panel = None # Add in each panel's views except for the default view. for panel in self._registry.values(): if panel.slug == self.default_panel: default_panel = panel continue url_slug = panel.slug.replace('.', '/') urlpatterns.append(url(r'^%s/' % url_slug, include(panel._decorated_urls))) # Now the default view, which should come last if not default_panel: raise NotRegistered('The default panel "%s" is not registered.' % self.default_panel) urlpatterns.append(url(r'', include(default_panel._decorated_urls))) # Require login if not public. if not self.public: _decorate_urlconf(urlpatterns, require_auth) # Apply access controls to all views in the patterns permissions = getattr(self, 'permissions', []) _decorate_urlconf(urlpatterns, require_perms, permissions) _decorate_urlconf(urlpatterns, _current_component, dashboard=self) # Return the three arguments to django.conf.urls.include return urlpatterns, self.slug, self.slug
def _urls(self): """Constructs the URLconf for Horizon from registered Dashboards.""" urlpatterns = self._get_default_urlpatterns() self._autodiscover() # Discover each dashboard's panels. for dash in self._registry.values(): dash._autodiscover() # Load the plugin-based panel configuration self._load_panel_customization() # Allow for override modules if self._conf.get("customization_module", None): customization_module = self._conf["customization_module"] bits = customization_module.split('.') mod_name = bits.pop() package = '.'.join(bits) mod = import_module(package) try: before_import_registry = copy.copy(self._registry) import_module('%s.%s' % (package, mod_name)) except Exception: self._registry = before_import_registry if module_has_submodule(mod, mod_name): raise # Compile the dynamic urlconf. for dash in self._registry.values(): urlpatterns.append(url(r'^%s/' % dash.slug, include(dash._decorated_urls))) # Return the three arguments to django.conf.urls.include return urlpatterns, self.namespace, self.slug
def get_urls(self): urlpatterns = [ url(r'', include(wagtail_urls)), ] return self.post_process_urls(urlpatterns)
def get_urls(self): urlpatterns = super(AdminoSite, self).get_urls() valid_app_labels = [] for model, model_admin in self._registry.items(): api_urlpatterns = [ url(r'^api/%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.api_urls)), ] urlpatterns = urlpatterns + api_urlpatterns if model._meta.app_label not in valid_app_labels: valid_app_labels.append(model._meta.app_label) return urlpatterns
def get_urls(self): from django.conf.urls import url, include from xadmin.views.base import BaseAdminView if settings.DEBUG: self.check_dependencies() def wrap(view, cacheable=False): def wrapper(*args, **kwargs): return self.admin_view(view, cacheable)(*args, **kwargs) return update_wrapper(wrapper, view) # Admin-site-wide views. urlpatterns = [ url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n') ] # Registed admin views # inspect[isclass]: Only checks if the object is a class. With it lets you create an custom view that # inherits from multiple views and have more of a metaclass. urlpatterns += [ url(path, wrap(self.create_admin_view(clz_or_func)) if inspect.isclass(clz_or_func) and issubclass(clz_or_func, BaseAdminView) else include(clz_or_func(self)), name=name) for path, clz_or_func, name in self._registry_views ] # Add in each model's views. for model, admin_class in self._registry.iteritems(): view_urls = [url( path, wrap( self.create_model_admin_view(clz, model, admin_class)), name=name % (model._meta.app_label, model._meta.model_name)) for path, clz, name in self._registry_modelviews] urlpatterns += [ url(r'^%s/%s/' % ( model._meta.app_label, model._meta.model_name), include(view_urls)) ] return urlpatterns
def get_urls(self): return [ url(r'^', include('django.contrib.auth.urls')), url(r'^parameters/edit/', self.user_parameters_update_view.as_view(), name='account-parameters'), url(r'^password/edit/', self.user_password_update_view.as_view(), name='account-password'), url(r'^register/', self.user_create_view.as_view(), name='register'), url(r'^unregister/$', self.user_delete_view.as_view(), name='unregister'), ]
def get_urls(self): urls = super(AGCSForumApp, self).get_urls() return urls + [ url(r'^account/', include(self.auth_app.urls)), ]
def test_include(self): """Make sure requires(A)(include(my_app.urls)) works.""" decorated_include = requires(A)(include(nested_urls2)) for pattern in decorated_include[0].urlpatterns: [cell] = [cell for cell in pattern.resolve.__closure__ if isinstance(cell.cell_contents, requires)] requirer = cell.cell_contents self.assertTrue( PermissionChecker(['a']).visit(requirer.gate.get_requires)) self.assertTrue( PermissionChecker(['a']).visit(requirer.gate.post_requires))
def get_urls(self): """Ensure that urls included in get_urls() are behind requires(). We need to fix the include() logic for admin URLs. Django admin isn't very extensible, so we have to call super, remove the url patterns for model_admins that have a _gate, and replace the pattern with a properly built include behind the model admin's gate. Would be a lot easier if django exposed something like get_patterns_for_app(app_label), but noooooo. """ # We have to maintain the URL ordering due to the way URLs are resolved # TODO - Test this, can lead to heisenbugs urls = OrderedDict((urlp.regex.pattern, urlp) for urlp in super(NestedGroupsAdminSite, self).get_urls()) for model, model_admin in self._get_admins_with_gate(): if hasattr(model._meta, 'module_name'): model_name = model._meta.module_name elif hasattr(model._meta, 'model_name'): model_name = model._meta.model_name else: raise ValueError( "Model Admin is missing a module or model name.") pattern = ( r'^%s/%s/' % (model._meta.app_label, model_name)) urls[pattern] = url( pattern, requires(get=model_admin._gate.get_requires, post=model_admin._gate.post_requires)( include(model_admin.urls))) return list(urls.values())
def include(module, namespace=None, app_name=None): from django.conf.urls import include if django.VERSION < (1,9): return include(module, namespace, app_name) else: return include((module, app_name), namespace)
def register_admin_urls(): return [ url(r'^relevancy/', include(urls)), ]
def register_admin_urls(): return [ url(r'^experiments/', include(admin_urls, app_name='experiments', namespace='experiments')), ]
def register_admin_urls(): return [ url(r'^analytics/', include(urls)), ]
def register_admin_urls(): return [ url(r'^surveys/', include(admin_urls, app_name='wagtailsurveys', namespace='wagtailsurveys')), ]
def get_urls(self): base_urls = super().get_urls() router = routers.DefaultRouter() router.register(r'offergroups', OfferGroupViewSet, base_name='api-offergroup') custom_urls = [ # API url(r'^api/', include(router.urls)), # Benefits url(r'^benefits/$', self.benefit_list_view.as_view(), name='benefit-list'), url(r'^benefits/new/$', self.benefit_create_view.as_view(), name='benefit-create'), url(r'^benefits/(?P<pk>[0-9]+)/$', self.benefit_update_view.as_view(), name='benefit-update'), url(r'^benefits/(?P<pk>[0-9]+)/delete/$', self.benefit_delete_view.as_view(), name='benefit-delete'), # Conditions url(r'^conditions/$', self.condition_list_view.as_view(), name='condition-list'), url(r'^conditions/new/$', self.condition_create_view.as_view(), name='condition-create'), url(r'^conditions/new-compound/$', self.compound_condition_create_view.as_view(), name='condition-create-compound'), url(r'^conditions/(?P<pk>[0-9]+)/$', self.condition_update_view.as_view(), name='condition-update'), url(r'^conditions/(?P<pk>[0-9]+)/delete/$', self.condition_delete_view.as_view(), name='condition-delete'), # Offer Groups url(r'^offer_group/$', self.offergroup_list_view.as_view(), name='offergroup-list'), url(r'^offer_group/new/$', self.offergroup_create_view.as_view(), name='offergroup-create'), url(r'^offer_group/(?P<pk>[0-9]+)/$', self.offergroup_update_view.as_view(), name='offergroup-update'), url(r'^offer_group/(?P<pk>[0-9]+)/delete/$', self.offergroup_delete_view.as_view(), name='offergroup-delete'), ] return base_urls + self.post_process_urls(custom_urls)
def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required): ret = [] for urlpattern in urlpatterns: if isinstance(urlpattern, RegexURLResolver): # Set of included URL patterns regex = urlpattern.regex.pattern namespace = urlpattern.namespace app_name = urlpattern.app_name kwargs = urlpattern.default_kwargs # Add in the included patterns, after applying the suffixes patterns = apply_suffix_patterns(urlpattern.url_patterns, suffix_pattern, suffix_required) ret.append(url(regex, include(patterns, namespace, app_name), kwargs)) else: # Regular URL pattern regex = urlpattern.regex.pattern.rstrip('$').rstrip('/') + suffix_pattern view = urlpattern._callback or urlpattern._callback_str kwargs = urlpattern.default_args name = urlpattern.name # Add in both the existing and the new urlpattern if not suffix_required: ret.append(urlpattern) ret.append(url(regex, view, kwargs, name)) return ret
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None): """ Supplement existing urlpatterns with corresponding patterns that also include a '.format' suffix. Retains urlpattern ordering. urlpatterns: A list of URL patterns. suffix_required: If `True`, only suffixed URLs will be generated, and non-suffixed URLs will not be used. Defaults to `False`. allowed: An optional tuple/list of allowed suffixes. eg ['json', 'api'] Defaults to `None`, which allows any suffix. """ suffix_kwarg = api_settings.FORMAT_SUFFIX_KWARG if allowed: if len(allowed) == 1: allowed_pattern = allowed[0] else: allowed_pattern = '(%s)' % '|'.join(allowed) suffix_pattern = r'\.(?P<%s>%s)/?$' % (suffix_kwarg, allowed_pattern) else: suffix_pattern = r'\.(?P<%s>[a-z0-9]+)/?$' % suffix_kwarg return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required)
def collect_urls(): urls = [] for app in collect_applications(): try: urls.append(url(r'^', include('{}.api.urls'.format(app)))) except ImportError: pass return urls
def register_admin_urls(): return [ url(r'^media/', include(admin_urls, app_name='wagtailmedia', namespace='wagtailmedia')), ]
def urls(self): ROOT_ROUTE = getattr(settings, 'API_ENDPOINT', 'api') return [ url(r'^{root_route}$'.format(root_route=ROOT_ROUTE), self.generate_root), url(r'^{root_route}/'.format(root_route=ROOT_ROUTE), include(self.register_models().urls, namespace='api')), ]
def default_urlpatterns(provider): login_view = import_attribute( provider.get_package() + '.views.oauth2_login') callback_view = import_attribute( provider.get_package() + '.views.oauth2_callback') urlpatterns = [ url('^login/$', login_view, name=provider.id + "_login"), url('^login/callback/$', callback_view, name=provider.id + "_callback"), ] return [url('^' + provider.get_slug() + '/', include(urlpatterns))]
def default_urlpatterns(provider): login_view = import_attribute( provider.get_package() + '.views.oauth_login') callback_view = import_attribute( provider.get_package() + '.views.oauth_callback') urlpatterns = [ url('^login/$', login_view, name=provider.id + "_login"), url('^login/callback/$', callback_view, name=provider.id + "_callback"), ] return [url('^' + provider.get_slug() + '/', include(urlpatterns))]
def register_admin_urls(): return [ url(r'^videos/', include(urls, namespace='wagtailvideos', app_name='wagtailvideos')), ]
def urls(self): """ ?? xadmin site ?urls?????django?urls??????????????Django? ``urls.py`` ????????:: from django.conf.urls import patterns, include, url import xadmin xadmin.autodiscover() urlpatterns = patterns('', url(r'', include(xadmin.site.urls)), ) """ return self.get_urls(), self.name, self.app_name
def register_admin_urls(): return [ url(r'^socialfeed/', include(urls, app_name='wagtailsocialfeed', namespace='wagtailsocialfeed')), ]
def get_urls(self): router = routers.DefaultRouter() router.register(r'access-rules', AccessRuleViewSet) router.register(r'meta-graph', MetaGraphView, base_name='metagraph') info = self.model._meta.app_label, self.model._meta.model_name urlpatterns = [ url(r'^neo4j/nodelist/$', self.get_nodelist_api_view, name='%s_%s_nodelist' % info), # Deprecated url(r'^neo4j/', include(router.urls)) ] + super(AccessRuleAdmin, self).get_urls() return urlpatterns
def test_flagged_url_true_include_true(self): response = self.get_url_response('/include/included-url') self.assertContains(response, 'view')