def modify_for_versioning(patterns, method, path, view, requested_version): assert view.versioning_class and view.request view.request.version = requested_version if issubclass(view.versioning_class, versioning.URLPathVersioning): version_param = view.versioning_class.version_param # substitute version variable to emulate request path = uritemplate.partial(path, var_dict={version_param: requested_version}) if isinstance(path, URITemplate): path = path.uri # emulate router behaviour by injecting substituted variable into view view.kwargs[version_param] = requested_version elif issubclass(view.versioning_class, versioning.NamespaceVersioning): try: view.request.resolver_match = get_resolver(urlconf=tuple( detype_pattern(p) for p in patterns)).resolve(path) except Resolver404: error( f"namespace versioning path resolution failed for {path}. path will be ignored." ) elif issubclass(view.versioning_class, versioning.AcceptHeaderVersioning): renderer = view.get_renderers()[0] view.request.META[ 'HTTP_ACCEPT'] = f'{renderer.media_type}; version={requested_version}' negotiated = view.perform_content_negotiation(view.request) view.request.accepted_renderer, view.request.accepted_media_type = negotiated return path
def get_all_url_patterns(): if get_all_url_patterns._cache: return get_all_url_patterns._cache else: get_all_url_patterns._cache = tuple( get_urls_from_resolver(get_resolver())) return get_all_url_patterns._cache
def modify_for_versioning(patterns, method, path, view, requested_version): assert view.versioning_class and view.request assert requested_version view.request.version = requested_version if issubclass(view.versioning_class, versioning.URLPathVersioning): version_param = view.versioning_class.version_param # substitute version variable to emulate request path = uritemplate.partial(path, var_dict={version_param: requested_version}) if isinstance(path, URITemplate): path = path.uri # emulate router behaviour by injecting substituted variable into view view.kwargs[version_param] = requested_version elif issubclass(view.versioning_class, versioning.NamespaceVersioning): try: view.request.resolver_match = get_resolver( urlconf=tuple(detype_pattern(p) for p in patterns) ).resolve(path) except Resolver404: error(f"namespace versioning path resolution failed for {path}. path will be ignored.") elif issubclass(view.versioning_class, versioning.AcceptHeaderVersioning): # Append the version into request accepted_media_type. # e.g "application/json; version=1.0" # To allow the AcceptHeaderVersioning negotiator going through. if not hasattr(view.request, 'accepted_renderer'): # Probably a mock request, content negotation was not performed, so, we do it now. negotiated = view.perform_content_negotiation(view.request) view.request.accepted_renderer, view.request.accepted_media_type = negotiated media_type = _MediaType(view.request.accepted_media_type) view.request.accepted_media_type = ( f'{media_type.full_type}; {view.versioning_class.version_param}={requested_version}' ) return path
def _invalidate_urlconf(self): """ To invalidate url patterns after plugin list mutated. The function will do the following things: + invalidate resolver's LRU cache (use `.cache_clear` provided by `lru_cache`) + reload main urlconf module and clear cache in biohub url patterns registration module + reload `urls.py` in each app, using a force-reload version of `autodiscover_module` + override default resolver's `urlconf_module` and `url_patterns` attributes, which are cached property and must be explicitly assigned """ from django.urls.resolvers import get_resolver import biohub.core.routes import biohub.main.urls try: get_resolver.cache_clear() biohub.core.routes.cache_clear() main_urls = importlib.reload(biohub.main.urls) resolver = get_resolver() resolver.urlconf_module = main_urls resolver.url_patterns = getattr(main_urls, "urlpatterns") except Exception as e: raise exceptions.URLConfError(e)
def collect_urls(self, urls=None, source=None, prefix=None): """Called recursively for URLResolver until base case URLPattern. Ultimately returning a list of data dicts. """ if urls is None: urls = resolvers.get_resolver() prefix = prefix or [] if isinstance(urls, resolvers.URLResolver): name = urls.urlconf_name if isinstance(name, (list, tuple)): name = '' elif not isinstance(name, str): name = name.__name__ source = urls.namespace or name.split('.')[0] or source res = [] for x in urls.url_patterns: res += self.collect_urls(x, source=source, prefix=prefix + [str(urls.pattern)]) return res elif isinstance(urls, resolvers.URLPattern): pattern = prefix + [str(urls.pattern)] pattern = ''.join([ea for ea in pattern if ea])[1:] data = [ source, urls.name, pattern, urls.lookup_str, dict(urls.default_args) ] return [dict(zip(self.all_columns, data))] else: raise ValueError(repr(urls))
def set_up_rest_resources(cls): # Must be here, because hanlers is not registered get_resolver().url_patterns resources_dict = model_resources_to_dict() rest_resources = [] for resource_name, resource in resources_dict.items(): if cls.get_model_label(resource.model) in cls.factories: add_urls_to_resource(resource) rest_resources.append( (resource_name, resource, resource.model)) elif not cls.ignore_warnings: cls.logger.warning( 'Model {} has not created factory class'.format( resource.model)) return rest_resources
class LoginView(FormView): template_name = "login.html" form_class = LoginForm success_url = get_resolver('success') def get_context_data(self, *args, **kwargs): """ 可以传递一些额外的内容到页面。 """ print("==============") context = super(LoginView, self).get_context_data(*args, **kwargs) context['active_page'] = 'login' print(context) return context def form_invalid(self, form): print("3333") def form_valid(self, form): print("2") user = form.login() if user: if user.is_active: login(self.request, user) return super(LoginView, self).form_valid() else: return self.response_error_page('你的账户未激活') else: return self.response_error_page('用户名或者密码错误') def response_error_page(self, msg): return render(self.request, 'error_page.html', {'message': msg})
def get_path_name(): """Collect names of path objects defined in all project urls.py. :return: {'name': 'url/of/path/object'} """ path_names = [ k for k in get_resolver(None).reverse_dict.keys() if isinstance(k, str) ] return dict((pn, reverse(pn)) for pn in path_names)
def reverse(*args, **kwargs): try: from django.core.urlresolvers import reverse return reverse(*args, **kwargs) except ModuleNotFoundError: # Django 1.11+ from django.urls.resolvers import get_resolver resolver = get_resolver() return resolver.reverse(*args, **kwargs)
def handle(self, *args, **options): modules = options.get('modules', []) for module in modules: from django.urls.resolvers import get_resolver module = get_resolver(module) router = Router(module) router.create_routes()
def set_up_main_views(cls): from is_core.site import registered_model_cores from is_core.main import UIRESTModelISCore # Must be here, because hanlers is not registered get_resolver().url_patterns ui_main_views = [] for main_view in [ model_view for model_view in registered_model_cores.values() if isinstance(model_view, UIRESTModelISCore) ]: model = main_view.model if cls.get_model_label(model) in cls.factories: ui_main_views.append((main_view, model)) elif not cls.ignore_warnings: cls.logger.warning( 'Model {} has not created factory class'.format(model)) return ui_main_views
def dispatch_urls(request, page, urls, path_rest): resolver = get_resolver(urls) resolver_match = resolver.resolve('/' + path_rest) callback, callback_args, callback_kwargs = resolver_match request.resolver_match = resolver_match callback_args = (page, ) + callback_args response = callback(request, *callback_args, **callback_kwargs) return response
def process_request(self, request): """ Check if the current site is in maintenance. """ # First check things that don't require a database access: # Allow access if remote ip is in INTERNAL_IPS if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS: return None # Check if the staff the user is allowed if hasattr(request, 'user'): if request.user.is_superuser: return None if not MAINTENANCE_BLOCK_STAFF and request.user.is_staff: return None # ok let's look at the db site = Site.objects.get_current() try: maintenance = Maintenance.objects.get(site=site) except Maintenance.DoesNotExist: # Allow access if no matching Maintenance object exists return None # Allow access if maintenance is not being performed if not maintenance.is_being_performed: return None # Check if a path is explicitly excluded from maintenance mode ignored_url_list = set(maintenance.ignored_url_patterns() + MAINTENANCE_ADMIN_IGNORED_URLS) ignored_url_patterns = tuple( re.compile(r'{}'.format(url)) for url in ignored_url_list) request_path = request.path_info.lstrip("/") for url in ignored_url_patterns: if url.match(request_path): return None # Otherwise show the user the 503 page resolver = resolvers.get_resolver(None) resolve = resolver.resolve_error_handler callback, param_dict = resolve('503') return callback(request, **param_dict)
def process_request(self, request): # Allow access if middleware is not activated allow_staff = getattr(settings, "MAINTENANCE_ALLOW_STAFF", True) allow_superuser = getattr(settings, "MAINTENANCE_ALLOW_SUPERUSER", True) if not (settings.MAINTENANCE_MODE or maintenance.status()): return None INTERNAL_IPS = maintenance.IPList(settings.INTERNAL_IPS) # Preferentially check HTTP_X_FORWARDED_FOR b/c a proxy # server might have obscured REMOTE_ADDR for ip in request.META.get("HTTP_X_FORWARDED_FOR", "").split(","): if ip.strip() in INTERNAL_IPS: return None # Allow access if remote ip is in INTERNAL_IPS if request.META.get("REMOTE_ADDR") in INTERNAL_IPS: return None # Allow access if the user doing the request is logged in and a # staff member. if hasattr(request, "user"): if allow_staff and request.user.is_staff: return None if allow_superuser and request.user.is_superuser: return None # Check if a path is explicitly excluded from maintenance mode for url in IGNORE_URLS: if url.match(request.path_info): return None # Otherwise show the user the 503 page if DJANGO_VERSION_MAJOR >= 3 and DJANGO_VERSION_MINOR >= 2: # Checks if DJANGO version is great than 3.2.0 for breaking change resolver = resolvers.get_resolver(None) resolve = resolver.resolve_error_handler callback = resolve('503') return callback(request) else: resolver = get_resolver() callback, param_dict = resolver.resolve_error_handler("503") return callback(request, **param_dict)
def reverse(*args, **kwargs): try: exception = ModuleNotFoundError except: ## py 3.6+ exception = ImportError try: from django.core.urlresolvers import reverse return reverse(*args, **kwargs) except exception: # Django 1.11+ from django.urls.resolvers import get_resolver resolver = get_resolver() return resolver.reverse(*args, **kwargs)
def process_django_view(app, what, name, obj, options, lines): res = get_resolver() flat_patterns = [] def walker(flat_patterns, urlpatterns, namespace=None): for pattern in urlpatterns: if hasattr(pattern, "url_patterns"): walker(flat_patterns, pattern.url_patterns, pattern.namespace) else: urlname = ("{}:{}".format(namespace, pattern.name) if namespace else pattern.name) flat_patterns.append([urlname, pattern.callback]) walker(flat_patterns, res.url_patterns) for urlname, callback in flat_patterns: if (hasattr(callback, "view_class") and callback.view_class == obj) or callback == obj: lines.append(":param url_name: ``%s``\n" % urlname) return lines
def collect_urls(urls=None, namespace=None, prefix=None): if urls is None: urls = resolvers.get_resolver() prefix = prefix or [] if isinstance(urls, resolvers.URLResolver): res = [] for x in urls.url_patterns: res += collect_urls(x, namespace=urls.namespace or namespace, prefix=prefix + [str(urls.pattern)]) return res elif isinstance(urls, resolvers.URLPattern): return [{ 'namespace': namespace, 'name': urls.name, 'pattern': prefix + [str(urls.pattern)], 'lookup_str': urls.lookup_str, 'default_args': dict(urls.default_args) }] else: raise NotImplementedError(repr(urls))
def run(self): url_resolver = get_resolver() self.options.setdefault('namespaces', []) self.options.setdefault('extra_urls', []) self.options.setdefault('application_packages', []) all_urls = [] def populate_level(urls, parents=None, namespace=None): if parents is None: parents = [] for url in urls.url_patterns: if isinstance(url, URLResolver): populate_level(url, parents + [url.pattern], namespace=(url.namespace or namespace)) elif isinstance(url, URLPattern): path = ' '.join(map(str, parents + [url.pattern])) cls = None if hasattr(url.callback, 'view_class'): cls = url.callback.view_class.__module__ + "." + url.callback.view_class.__name__ # pending_xref() all_urls.append([ nodes.Text(path), nodes.Text(namespace or '-'), nodes.Text(str(url.name)), nodes.Text(cls), ]) populate_level(url_resolver) all_urls = filter(lambda url: url[1] in self.options['namespaces'] or url[0] in self.options['extra_urls'] or any(filter(lambda pkg: str.startswith(url[3], pkg), self.options['application_packages'])), all_urls) return [self.build_table_from_list(all_urls, ['Pattern', 'Namespace', 'Name', 'Class'])]
def modify_for_versioning(patterns, method, path, view, requested_version): assert view.versioning_class from rest_framework.test import APIRequestFactory params = {'path': path} if issubclass(view.versioning_class, versioning.AcceptHeaderVersioning): renderer = view.get_renderers()[0] params['HTTP_ACCEPT'] = f'{renderer.media_type}; version={requested_version}' request = getattr(APIRequestFactory(), method.lower())(**params) view.request = request # wrap request in DRF's Request, necessary for content negotiation view.request = view.initialize_request(view.request) request.version = requested_version if issubclass(view.versioning_class, versioning.URLPathVersioning): version_param = view.versioning_class.version_param # substitute version variable to emulate request path = uritemplate.partial(path, var_dict={version_param: requested_version}) if isinstance(path, URITemplate): path = path.uri # emulate router behaviour by injecting substituted variable into view view.kwargs[version_param] = requested_version elif issubclass(view.versioning_class, versioning.NamespaceVersioning): try: request.resolver_match = get_resolver( urlconf=tuple(detype_pattern(p) for p in patterns) ).resolve(path) except Resolver404: error(f"namespace versioning path resolution failed for {path}. path will be ignored.") elif issubclass(view.versioning_class, versioning.AcceptHeaderVersioning): neg = view.perform_content_negotiation(view.request) view.request.accepted_renderer, view.request.accepted_media_type = neg return path
def modify_for_versioning(patterns, method, path, view, requested_version): assert view.versioning_class from rest_framework.test import APIRequestFactory mocked_request = getattr(APIRequestFactory(), method.lower())(path=path) view.request = mocked_request mocked_request.version = requested_version if issubclass(view.versioning_class, versioning.URLPathVersioning): version_param = view.versioning_class.version_param # substitute version variable to emulate request path = uritemplate.partial(path, var_dict={version_param: requested_version}) if isinstance(path, URITemplate): path = path.uri # emulate router behaviour by injecting substituted variable into view view.kwargs[version_param] = requested_version elif issubclass(view.versioning_class, versioning.NamespaceVersioning): mocked_request.resolver_match = get_resolver( tuple(patterns)).resolve(path) return path
def _resolve_django2x(path, resolver=None): """Resolve a given path to its matching regex (Django 2.x). This is essentially a re-implementation of ``URLResolver.resolve`` that builds and returns the matched regex instead of the view itself. >>> _resolve_django2x('/api/1.0/patches/1/checks/') "^api/(?:(?P<version>(1.0|1.1))/)patches/(?P<patch_id>[^/]+)/checks/$" """ from django.urls.resolvers import URLResolver # noqa from django.urls.resolvers import RegexPattern # noqa resolver = resolver or get_resolver() match = resolver.pattern.match(path) # we dont handle any other type of pattern at the moment assert isinstance(resolver.pattern, RegexPattern) if not match: return if isinstance(resolver, URLResolver): sub_path, args, kwargs = match for sub_resolver in resolver.url_patterns: sub_match = _resolve_django2x(sub_path, sub_resolver) if not sub_match: continue kwargs.update(sub_match[2]) args += sub_match[1] regex = resolver.pattern._regex + sub_match[0].lstrip('^') return regex, args, kwargs else: _, args, kwargs = match return resolver.pattern._regex, args, kwargs
def _resolve_django1x(path, resolver=None): """Resolve a given path to its matching regex (Django 1.x). This is essentially a re-implementation of ``RegexURLResolver.resolve`` that builds and returns the matched regex instead of the view itself. >>> _resolve_django1x('/api/1.0/patches/1/checks/') "^api/(?:(?P<version>(1.0|1.1))/)patches/(?P<patch_id>[^/]+)/checks/$" """ from django.urls.resolvers import RegexURLResolver # noqa resolver = resolver or get_resolver() match = resolver.regex.search(path) if not match: return if isinstance(resolver, RegexURLResolver): sub_path = path[match.end():] for sub_resolver in resolver.url_patterns: sub_match = _resolve_django1x(sub_path, sub_resolver) if not sub_match: continue kwargs = dict(match.groupdict()) kwargs.update(sub_match[2]) args = sub_match[1] if not kwargs: args = match.groups() + args regex = resolver.regex.pattern + sub_match[0].lstrip('^') return regex, args, kwargs else: # RegexURLPattern kwargs = match.groupdict() args = () if kwargs else match.groups() return resolver.regex.pattern, args, kwargs
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) choices = [("", "-- All Pages --")] choices.extend(url_choices(get_resolver(None))) self.fields["view"].widget = forms.Select(choices=choices)
def resolve_to_name(path, urlconf=None): try: return _resolver_resolve_to_name(get_resolver(urlconf), path) except Resolver404: return None
def show_urls(request): resolver = get_resolver(urls) url_info = os.popen( 'python ./manage.py show_urls |grep cmcaifu.apps.api.views |grep api/v2' ) info = '' f = open('/tmp/service.java', 'a') for url in url_info.readlines(): url_list = url.strip().split('\t') seriaizer_obj = 'views.{}'.format(url_list[1].replace( 'cmcaifu.apps.api.views.', '')) if getattr(eval(seriaizer_obj), 'serializer_class', None): class_name = get_class_name(url_list[1].replace( 'cmcaifu.apps.api.views.', '')) method_list = dir( eval('views.{}'.format(url_list[1].replace( 'cmcaifu.apps.api.views.', '')))) serializer_name = eval('views.{}.serializer_class'.format( url_list[1].replace('cmcaifu.apps.api.views.', ''))) if getattr(serializer_name, 'Meta', None): model_name = eval( 'views.{}.serializer_class.Meta.model.__name__'.format( url_list[1].replace('cmcaifu.apps.api.views.', ''))) else: if 'DetailSerializer' in eval( 'views.{}.serializer_class.__name__'.format( url_list[1].replace('cmcaifu.apps.api.views.', ''))): model_name = eval( 'views.{}.serializer_class.__name__'.format( url_list[1].replace('cmcaifu.apps.api.views.', '')))[:-16] if 'ListSerializer' in eval( 'views.{}.serializer_class.__name__'.format( url_list[1].replace('cmcaifu.apps.api.views.', ''))): model_name = eval( 'views.{}.serializer_class.__name__'.format( url_list[1].replace('cmcaifu.apps.api.views.', '')))[:-14] else: model_name = eval( 'views.{}.serializer_class.__name__'.format( url_list[1].replace('cmcaifu.apps.api.views.', '')))[:-10] if 'list' in method_list: if 'pk' in url_list[0]: if 'cards' in url_list[0]: write_to_file(f, 'LIST', url_list[0], model_name, class_name, 'id', 'Long') else: write_to_file(f, 'LIST', url_list[0], model_name, class_name, 'id', 'Int') elif 'name' in url_list[0]: write_to_file(f, 'LIST', url_list[0], model_name, class_name, 'name', 'String') else: write_to_file(f, 'LIST', url_list[0], model_name, class_name) if 'retrieve' in method_list: if 'pk' in url_list[0]: if 'cards' in url_list[0]: write_to_file(f, 'GET', url_list[0], model_name, class_name, 'id', 'Long') else: write_to_file(f, 'GET', url_list[0], model_name, class_name, 'id', 'Int') elif 'name' in url_list[0]: write_to_file(f, 'GET', url_list[0], model_name, class_name, 'name', 'String') else: pass if 'create' in method_list: write_to_file(f, 'POST', url_list[0], model_name, class_name, '{}'.format(model_name), '{}'.format(model_name.lower())) if 'put' in method_list: if 'pk' in url_list[0]: if 'cards' in url_list[0]: write_to_file(f, 'PUT', url_list[0], model_name, class_name, 'id', 'Long') else: write_to_file(f, 'PUT', url_list[0], model_name, class_name, 'id', 'Int') elif 'name' in url_list[0]: write_to_file(f, 'PUT', url_list[0], model_name, class_name, 'name', 'String') else: pass if 'delete' in method_list: if 'pk' in url_list[0]: if 'cards' in url_list[0]: write_to_file(f, 'DELETE', url_list[0], model_name, class_name, 'id', 'Long') else: write_to_file(f, 'DELETE', url_list[0], model_name, class_name, 'id', 'Int') elif 'name' in url_list[0]: write_to_file(f, 'DELETE', url_list[0], model_name, class_name, 'name', 'String') else: pass f.close() return render(request, 'show_urls.html', locals())
def test_resolver_cache_default__root_urlconf(self): # resolver for a default URLconf (passing no argument) and for the # settings.ROOT_URLCONF is the same cached object. self.assertIs(get_resolver(), get_resolver('urlpatterns.path_urls')) self.assertIsNot(get_resolver(), get_resolver('urlpatterns.path_dynamic_urls'))
def _get_patterns(self): resolver = get_resolver(self.urlconf) return self.populate(resolver)
import logging from django.urls.resolvers import get_resolver from .log_operator_content_dict import VerifyUrlSaveContent from rest_framework.response import Response from django.http import FileResponse from nms_server.dao.opr_log import operate_log logger = logging.getLogger("nms." + __name__) CONST_METHODS = dict(GET="查看", POST="新增", PUT="修改", DELETE="删除") URL_REGEX = get_resolver() def logStashMiddleware(get_response): def middleware(request): response = get_response(request) if request.path.startswith('/nms/check'): return response try: verify_url_save_content = VerifyUrlSaveContent(request, response) detail = verify_url_save_content.run() if detail is not None: operate_log(detail) except Exception as e: logger.error(e) pass return response return middleware
def get_static_urls(): urls = {} client = Client() excludes = [ re.compile(r) for r in settings.NOINDEX_URLS + [ r'.*%\(.*\).*', r'.*//$', r'^media/', r'^robots\.txt$', # Redirects in en-US. Added via EXTRA_INDEX_URLS r'firefox-klar/$', ] ] # start with the ones we know we want urls.update(settings.EXTRA_INDEX_URLS) # get_resolver is an undocumented but convenient function. # Try to retrieve all valid URLs on this site. # NOTE: have to use `lists()` here since the standard # `items()` only returns the first item in the list for the # view since `reverse_dict` is a `MultiValueDict`. for key, values in resolvers.get_resolver(None).reverse_dict.lists(): for value in values: path = value[0][0][0] # Exclude pages that we don't want be indexed by search engines. # Some other URLs are also unnecessary for the sitemap. if any(exclude.search(path) for exclude in excludes): continue path_prefix = path.split('/', 2)[0] nonlocale = path_prefix in settings.SUPPORTED_NONLOCALES path = '/%s' % path if nonlocale: locales = [] else: with patch('lib.l10n_utils.django_render') as render: render.return_value = HttpResponse() client.get('/' + settings.LANGUAGE_CODE + path) # Exclude urls that did not call render if not render.called: continue locales = set(render.call_args[0][2]['translations'].keys()) # zh-CN is a redirect on the homepage if path == '/': locales -= {'zh-CN'} # Firefox Focus has a different URL in German if path == '/privacy/firefox-focus/': locales -= {'de'} # just remove any locales not in our prod list locales = list(locales.intersection(settings.PROD_LANGUAGES)) if path not in urls: urls[path] = locales return urls
def test_root_url_resolves_to_home_page_view(self) -> None: found = get_resolver().resolve('/') self.assertEqual(found.func, home_page)