def process_request(self, request):
try:
request.META["LoadingStart"] = time.time()
host = request.META["HTTP_HOST"]
#if host[-3:] == ":80":
# host = host[:-3] # ignore default port number, if present
# best way to do this.
host_port = host.split(':')
if len(host_port)==2:
host = host_port[0]
if host in settings.HOST_MIDDLEWARE_URLCONF_MAP:
request.urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[host]
request.META["MultiHost"] = str(request.urlconf)
else:
request.META["MultiHost"] = str(settings.ROOT_URLCONF)
except KeyError:
pass # use default urlconf (settings.ROOT_URLCONF)
python类ROOT_URLCONF的实例源码
def reload_urls(self):
"""
Code borrowed from ApphooksTestCase
"""
from django.conf import settings
url_modules = [
'cms.urls',
# TODO: Add here intermediary modules which may
# include() the 'cms.urls' if it isn't included
# directly in the root urlconf.
# '...',
'cms.test_utils.project.second_cms_urls_for_apphook_tests',
'cms.test_utils.project.urls_for_apphook_tests',
settings.ROOT_URLCONF,
]
clear_app_resolvers()
clear_url_caches()
for module in url_modules:
if module in sys.modules:
del sys.modules[module]
def reload_urls(self):
from django.conf import settings
url_modules = [
'cms.urls',
# TODO: Add here intermediary modules which may
# include() the 'cms.urls' if it isn't included
# directly in the root urlconf.
# '...',
'cms.test_utils.project.second_cms_urls_for_apphook_tests',
'cms.test_utils.project.urls_for_apphook_tests',
settings.ROOT_URLCONF,
]
clear_app_resolvers()
clear_url_caches()
for module in url_modules:
if module in sys.modules:
del sys.modules[module]
def active_user(request, token): # ??????
try:
username = token_confirm.confirm_validate_token(token)
except:
username = token_confirm.remove_validate_token(token)
users = User.objects.filter(username=username)
for user in users:
user.delete()
return render(request, 'message.html',
{'message': u'????????????????<a href=\"' + unicode(settings.DOMAIN) + u'/signup\">??</a>'})
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
return render(request, 'message.html', {'message': u"????????????????????"})
user.is_active = True
user.save()
message = u'????????<a href=\"' + unicode(settings.ROOT_URLCONF) + u'/login\">??</a>??'
return render(request, 'message.html', {'message':message})
def discover_tree(urlconf=None):
"""Finds all ApiNode usage in given or default urlconf"""
if urlconf is None:
urlconf = settings.ROOT_URLCONF
if isinstance(urlconf, basestring):
urlconf = import_module(urlconf)
nodes = set()
for item in urlconf.urlpatterns:
for p in item.url_patterns:
if has_descent_attrs(p.callback, 'im_self', 'get_root_class'):
nodes.add(p.callback.im_self.get_root_class())
return nodes
def discover_tree(urlconf=None):
"""Finds all ApiNode usage in given or default urlconf"""
if urlconf is None:
urlconf = settings.ROOT_URLCONF
if isinstance(urlconf, basestring):
urlconf = import_module(urlconf)
nodes = set()
for item in urlconf.urlpatterns:
for p in item.url_patterns:
if has_descent_attrs(p.callback, 'im_self', 'get_root_class'):
nodes.add(p.callback.im_self.get_root_class())
return nodes
def discover_tree(urlconf=None):
"""Finds all ApiNode usage in given or default urlconf"""
if urlconf is None:
urlconf = settings.ROOT_URLCONF
if isinstance(urlconf, basestring):
urlconf = import_module(urlconf)
nodes = set()
for item in urlconf.urlpatterns:
for p in item.url_patterns:
if has_descent_attrs(p.callback, 'im_self', 'get_root_class'):
nodes.add(p.callback.im_self.get_root_class())
return nodes
def test_get_apis(self):
urls = import_module(settings.ROOT_URLCONF)
# Overwrite settings with test patterns
urls.urlpatterns = self.url_patterns
apis = self.urlparser.get_apis()
self.assertEqual(self.url_patterns[0], apis[0]['pattern'])
self.assertEqual('/a-view/', apis[0]['path'])
self.assertEqual(self.url_patterns[1], apis[1]['pattern'])
self.assertEqual('/b-view', apis[1]['path'])
self.assertEqual(self.url_patterns[2], apis[2]['pattern'])
self.assertEqual('/c-view/', apis[2]['path'])
self.assertEqual(self.url_patterns[3], apis[3]['pattern'])
self.assertEqual('/a-view/child/', apis[3]['path'])
self.assertEqual(self.url_patterns[4], apis[4]['pattern'])
self.assertEqual('/a-view/child2/', apis[4]['path'])
self.assertEqual(self.url_patterns[5], apis[5]['pattern'])
self.assertEqual('/another-view/', apis[5]['path'])
self.assertEqual(self.url_patterns[6], apis[6]['pattern'])
self.assertEqual('/view-with-param/{var}/', apis[6]['path'])
def test_get_apis_urlconf(self):
urls = import_module(settings.ROOT_URLCONF)
# Overwrite settings with test patterns
urls.urlpatterns = self.url_patterns
apis = self.urlparser.get_apis(urlconf=urls)
self.assertEqual(self.url_patterns[0], apis[0]['pattern'])
self.assertEqual('/a-view/', apis[0]['path'])
self.assertEqual(self.url_patterns[1], apis[1]['pattern'])
self.assertEqual('/b-view', apis[1]['path'])
self.assertEqual(self.url_patterns[2], apis[2]['pattern'])
self.assertEqual('/c-view/', apis[2]['path'])
self.assertEqual(self.url_patterns[3], apis[3]['pattern'])
self.assertEqual('/a-view/child/', apis[3]['path'])
self.assertEqual(self.url_patterns[4], apis[4]['pattern'])
self.assertEqual('/a-view/child2/', apis[4]['path'])
self.assertEqual(self.url_patterns[5], apis[5]['pattern'])
self.assertEqual('/another-view/', apis[5]['path'])
self.assertEqual(self.url_patterns[6], apis[6]['pattern'])
self.assertEqual('/view-with-param/{var}/', apis[6]['path'])
def get_apis(self, url_patterns=None, urlconf=None, filter_path=None, exclude_namespaces=None):
"""
Returns all the DRF APIViews found in the project URLs
patterns -- supply list of patterns (optional)
exclude_namespaces -- list of namespaces to ignore (optional)
"""
if not url_patterns and urlconf:
if isinstance(urlconf, six.string_types):
urls = import_module(urlconf)
else:
urls = urlconf
url_patterns = urls.urlpatterns
elif not url_patterns and not urlconf:
urls = import_module(settings.ROOT_URLCONF)
url_patterns = urls.urlpatterns
formatted_apis = self.format_api_patterns(
url_patterns,
filter_path=filter_path,
exclude_namespaces=exclude_namespaces,
)
return formatted_apis
def createTempViewURL():
# add the TempView to the urlpatterns
global urlpatterns
urlpatterns += [
url(r'^temp/?', TempView.as_view(), name='temp'),
]
# reload the urlpatterns
urlconf = settings.ROOT_URLCONF
if urlconf in sys.modules:
reload(sys.modules[urlconf])
reloaded = import_module(urlconf)
reloaded_urls = getattr(reloaded, 'urlpatterns')
set_urlconf(tuple(reloaded_urls))
# return the temporary URL
return reverse('temp')
def reload_url_conf():
# Reload URLs to pick up the overridden settings
if settings.ROOT_URLCONF in sys.modules:
reload(sys.modules[settings.ROOT_URLCONF])
import_module(settings.ROOT_URLCONF)
clear_url_caches()
def setUp(self):
super(ThemePreviewTests, self).setUp()
urlresolvers.clear_url_caches()
moves.reload_module(import_module(settings.ROOT_URLCONF))
base.Horizon.register(Developer)
base.Horizon._urls()
def _reload_urls(self):
"""CLeans up URLs.
Clears out the URL caches, reloads the root urls module, and
re-triggers the autodiscovery mechanism for Horizon. Allows URLs
to be re-calculated after registering new dashboards. Useful
only for testing and should never be used on a live site.
"""
urlresolvers.clear_url_caches()
moves.reload_module(import_module(settings.ROOT_URLCONF))
base.Horizon._urls()
def _reload_urls(self):
"""Clears out the URL caches, reloads the root urls module, and
re-triggers the autodiscovery mechanism for Horizon. Allows URLs
to be re-calculated after registering new dashboards. Useful
only for testing and should never be used on a live site.
"""
urlresolvers.clear_url_caches()
moves.reload_module(import_module(settings.ROOT_URLCONF))
base.Horizon._urls()
def get_resolver(urlconf=None):
if urlconf is None:
from django.conf import settings
urlconf = settings.ROOT_URLCONF
return RegexURLResolver(r'^/', urlconf)
def get_context_data(self, **kwargs):
views = []
urlconf = import_module(settings.ROOT_URLCONF)
view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
for (func, regex, namespace, name) in view_functions:
views.append({
'full_name': '%s.%s' % (func.__module__, getattr(func, '__name__', func.__class__.__name__)),
'url': simplify_regex(regex),
'url_name': ':'.join((namespace or []) + (name and [name] or [])),
'namespace': ':'.join((namespace or [])),
'name': name,
})
kwargs.update({'views': views})
return super(ViewIndexView, self).get_context_data(**kwargs)
def _pre_setup(self):
"""Performs any pre-test setup. This includes:
* Creating a test client.
* If the class has a 'urls' attribute, replace ROOT_URLCONF with it.
* Clearing the mail test outbox.
"""
self.client = self.client_class()
self._urlconf_setup()
mail.outbox = []
def _urlconf_setup(self):
if hasattr(self, 'urls'):
warnings.warn(
"SimpleTestCase.urls is deprecated and will be removed in "
"Django 1.10. Use @override_settings(ROOT_URLCONF=...) "
"in %s instead." % self.__class__.__name__,
RemovedInDjango110Warning, stacklevel=2)
set_urlconf(None)
self._old_root_urlconf = settings.ROOT_URLCONF
settings.ROOT_URLCONF = self.urls
clear_url_caches()
def _post_teardown(self):
"""Performs any post-test things. This includes:
* Putting back the original ROOT_URLCONF if it was changed.
"""
self._urlconf_teardown()
def get_response(self, request):
"""Return an HttpResponse object for the given HttpRequest."""
# Setup default url resolver for this thread
set_urlconf(settings.ROOT_URLCONF)
response = self._middleware_chain(request)
# This block is only needed for legacy MIDDLEWARE_CLASSES; if
# MIDDLEWARE is used, self._response_middleware will be empty.
try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
# Complain if the response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__))
except Exception: # Any exception should be gathered and handled
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
response._closable_objects.append(request)
# If the exception handler returns a TemplateResponse that has not
# been rendered, force it to be rendered.
if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)):
response = response.render()
if response.status_code == 404:
logger.warning(
'Not Found: %s', request.path,
extra={'status_code': 404, 'request': request},
)
return response
def get_context_data(self, **kwargs):
views = []
urlconf = import_module(settings.ROOT_URLCONF)
view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
for (func, regex, namespace, name) in view_functions:
views.append({
'full_name': self._get_full_name(func),
'url': simplify_regex(regex),
'url_name': ':'.join((namespace or []) + (name and [name] or [])),
'namespace': ':'.join((namespace or [])),
'name': name,
})
kwargs.update({'views': views})
return super(ViewIndexView, self).get_context_data(**kwargs)
def get_response(self, request):
"""Return an HttpResponse object for the given HttpRequest."""
# Setup default url resolver for this thread
set_urlconf(settings.ROOT_URLCONF)
response = self._middleware_chain(request)
# This block is only needed for legacy MIDDLEWARE_CLASSES; if
# MIDDLEWARE is used, self._response_middleware will be empty.
try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
# Complain if the response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__))
except Exception: # Any exception should be gathered and handled
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
response._closable_objects.append(request)
# If the exception handler returns a TemplateResponse that has not
# been rendered, force it to be rendered.
if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)):
response = response.render()
if response.status_code == 404:
logger.warning(
'Not Found: %s', request.path,
extra={'status_code': 404, 'request': request},
)
return response
def get_context_data(self, **kwargs):
views = []
urlconf = import_module(settings.ROOT_URLCONF)
view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
for (func, regex, namespace, name) in view_functions:
views.append({
'full_name': self._get_full_name(func),
'url': simplify_regex(regex),
'url_name': ':'.join((namespace or []) + (name and [name] or [])),
'namespace': ':'.join((namespace or [])),
'name': name,
})
kwargs.update({'views': views})
return super(ViewIndexView, self).get_context_data(**kwargs)
def get_response(self, request):
"""Return an HttpResponse object for the given HttpRequest."""
# Setup default url resolver for this thread
set_urlconf(settings.ROOT_URLCONF)
response = self._middleware_chain(request)
# This block is only needed for legacy MIDDLEWARE_CLASSES; if
# MIDDLEWARE is used, self._response_middleware will be empty.
try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
# Complain if the response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__))
except Exception: # Any exception should be gathered and handled
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
response._closable_objects.append(request)
# If the exception handler returns a TemplateResponse that has not
# been rendered, force it to be rendered.
if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)):
response = response.render()
if response.status_code == 404:
logger.warning(
'Not Found: %s', request.path,
extra={'status_code': 404, 'request': request},
)
return response
def get_context_data(self, **kwargs):
views = []
urlconf = import_module(settings.ROOT_URLCONF)
view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
for (func, regex, namespace, name) in view_functions:
views.append({
'full_name': self._get_full_name(func),
'url': simplify_regex(regex),
'url_name': ':'.join((namespace or []) + (name and [name] or [])),
'namespace': ':'.join((namespace or [])),
'name': name,
})
kwargs.update({'views': views})
return super(ViewIndexView, self).get_context_data(**kwargs)
def __init__(self, patterns=None, urlconf=None):
if patterns is None:
if urlconf is None:
# Use the default Django URL conf
urlconf = settings.ROOT_URLCONF
# Load the given URLconf module
if isinstance(urlconf, six.string_types):
urls = import_module(urlconf)
else:
urls = urlconf
patterns = urls.urlpatterns
self.patterns = patterns
def handle(self, *args, **options):
root_urlconf = __import__(settings.ROOT_URLCONF)
patterns = root_urlconf.urls.urlpatterns
global full_url
for pat in patterns:
if pat.__class__.__name__ == 'RegexURLResolver':
url_root_res = str(pat).split('^')[1].replace('>', '')
if 'gui' in url_root_res:
for url_patt in pat.url_patterns:
full_url = self.get_full_url(url_patt, url_root_res)
info = self.url_info(full_url)
status_code = info[0]
load_time = info[1]
print('Trying \'' + full_url + '\', ' + str(status_code) + ', ' + str(load_time))
def get_response(self, request):
"""Return an HttpResponse object for the given HttpRequest."""
# Setup default url resolver for this thread
set_urlconf(settings.ROOT_URLCONF)
response = self._middleware_chain(request)
# This block is only needed for legacy MIDDLEWARE_CLASSES; if
# MIDDLEWARE is used, self._response_middleware will be empty.
try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
# Complain if the response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__))
except Exception: # Any exception should be gathered and handled
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
response._closable_objects.append(request)
# If the exception handler returns a TemplateResponse that has not
# been rendered, force it to be rendered.
if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)):
response = response.render()
if response.status_code == 404:
logger.warning(
'Not Found: %s', request.path,
extra={'status_code': 404, 'request': request},
)
return response
def get_context_data(self, **kwargs):
views = []
urlconf = import_module(settings.ROOT_URLCONF)
view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
for (func, regex, namespace, name) in view_functions:
views.append({
'full_name': self._get_full_name(func),
'url': simplify_regex(regex),
'url_name': ':'.join((namespace or []) + (name and [name] or [])),
'namespace': ':'.join((namespace or [])),
'name': name,
})
kwargs.update({'views': views})
return super(ViewIndexView, self).get_context_data(**kwargs)