本文整理汇总了Python中django.core.handlers.base.BaseHandler类的典型用法代码示例。如果您正苦于以下问题:Python BaseHandler类的具体用法?Python BaseHandler怎么用?Python BaseHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BaseHandler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_is_authenticated
def test_is_authenticated(self):
auth = DjangoAuthentication()
request = self.factory.get("/")
# load the middleware since django doesnt...
from django.core.handlers.base import BaseHandler
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
self.assertIsNone(middleware_method(request))
# not logged in should fail
self.assertFalse(auth.is_authenticated(request))
# not logged in should be AnonymousUser
self.assertEquals(auth.get_identifier(request), "AnonymousUser")
# login test user
from django.contrib.auth import authenticate, login
user = authenticate(username="janeroe", password="qwe123")
self.assertIsNotNone(user)
login(request, user)
# logged in should succeed
self.assertTrue(auth.is_authenticated(request))
# should be janeroe logged in
self.assertEquals(auth.get_identifier(request), "janeroe")
示例2: request
def request(self, **request_args):
"""Constructs a generic request object, INCLUDING middleware modifications."""
from django.core import urlresolvers
request = RequestFactory.request(self, **request_args)
###pprint.pprint(request)
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
#print("APPLYING REQUEST MIDDLEWARE ", middleware_method, file=sys.stderr)
if middleware_method(request):
raise Exception("Couldn't create request mock object - "
"request middleware returned a response")
urlconf = settings.ROOT_URLCONF
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
callback, callback_args, callback_kwargs = resolver.resolve(
request.path_info)
# Apply view middleware
for middleware_method in handler._view_middleware:
#print("APPLYING VIEW MIDDLEWARE ", middleware_method, file=sys.stderr)
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
raise Exception("Couldn't create request mock object - "
"view middleware returned a response")
return request
示例3: dummy_request
def dummy_request(self):
"""
Construct a HttpRequest object that is, as far as possible, representative of ones that would
receive this page as a response. Used for previewing / moderation and any other place where we
want to display a view of this page in the admin interface without going through the regular
page routing logic.
"""
url = self.full_url
if url:
url_info = urlparse(url)
hostname = url_info.netloc
path = url_info.path
port = url_info.port or 80
else:
hostname = 'example.com'
path = '/'
port = 80
request = WSGIRequest({
'REQUEST_METHOD': 'GET',
'PATH_INFO': path,
'SERVER_NAME': hostname,
'SERVER_PORT': port,
'wsgi.input': StringIO(),
})
# Apply middleware to the request - see http://www.mellowmorning.com/2011/04/18/mock-django-request-for-testing/
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
if middleware_method(request):
raise Exception("Couldn't create request mock object - "
"request middleware returned a response")
return request
示例4: MessageSenderWorker
class MessageSenderWorker(QueueProcessingWorker):
def __init__(self):
# type: () -> None
super().__init__()
self.redis_client = get_redis_client()
self.handler = BaseHandler()
self.handler.load_middleware()
def consume(self, event):
# type: (Mapping[str, Any]) -> None
server_meta = event['server_meta']
environ = {
'REQUEST_METHOD': 'SOCKET',
'SCRIPT_NAME': '',
'PATH_INFO': '/json/messages',
'SERVER_NAME': '127.0.0.1',
'SERVER_PORT': 9993,
'SERVER_PROTOCOL': 'ZULIP_SOCKET/1.0',
'wsgi.version': (1, 0),
'wsgi.input': StringIO(),
'wsgi.errors': sys.stderr,
'wsgi.multithread': False,
'wsgi.multiprocess': True,
'wsgi.run_once': False,
'zulip.emulated_method': 'POST'
}
if 'socket_user_agent' in event['request']:
environ['HTTP_USER_AGENT'] = event['request']['socket_user_agent']
del event['request']['socket_user_agent']
# We're mostly using a WSGIRequest for convenience
environ.update(server_meta['request_environ'])
request = WSGIRequest(environ)
# Note: If we ever support non-POST methods, we'll need to change this.
request._post = event['request']
request.csrf_processing_done = True
user_profile = get_user_profile_by_id(server_meta['user_id'])
request._cached_user = user_profile
resp = self.handler.get_response(request)
server_meta['time_request_finished'] = time.time()
server_meta['worker_log_data'] = request._log_data
resp_content = resp.content.decode('utf-8')
response_data = ujson.loads(resp_content)
if response_data['result'] == 'error':
check_and_send_restart_signal()
result = {'response': response_data, 'req_id': event['req_id'],
'server_meta': server_meta}
redis_key = req_redis_key(event['req_id'])
self.redis_client.hmset(redis_key, {'status': 'complete',
'response': resp_content})
queue_json_publish(server_meta['return_queue'], result,
respond_send_message)
示例5: test_error_handlers
def test_error_handlers(rf):
"""
Test that SHOOP_FRONT_INSTALL_ERROR_HANDLERS installs error handlers
without overwriting possible custom ones.
"""
with override_settings(
DEBUG=False,
SHOOP_FRONT_INSTALL_ERROR_HANDLERS=True,
MIDDLEWARE_CLASSES=[]
):
with replace_urls([
url("^aaargh/", errorful_view)
], {"handler404": four_oh_four}):
resolver = get_resolver(None)
urlconf = resolver.urlconf_module
install_error_handlers()
assert callable(urlconf.handler500) # We get a new 500 handler
assert urlconf.handler404 == four_oh_four # Our custom 404 handler didn't get overwritten
handler = BaseHandler()
handler.load_middleware()
# Test 500
response = handler.get_response(rf.get("/aaargh/"))
assert response.status_code == 500 # Uh oh!
assert isinstance(response, TemplateResponse) # Looks good!
assert response.template_name.startswith("shoop") # Woop!
# Test 404
response = handler.get_response(rf.get("/another_castle/"))
assert response.status_code == 200 # Our custom 404 handler made it a 200!
assert b"flesh wound" in response.content
示例6: _prepare_request
def _prepare_request(self, request, page, user, lang, use_middlewares, use_toolbar=False):
request.current_page = SimpleLazyObject(lambda: page)
if not user:
if self._login_context:
user = self._login_context.user
else:
user = AnonymousUser()
request.user = user
request.session = {}
request.cookies = SimpleCookie()
request.errors = StringIO()
request.LANGUAGE_CODE = lang
# Let's use middleware in case requested, otherwise just use CMS toolbar if needed
if use_middlewares:
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
if middleware_method(request):
raise Exception(u'Couldn\'t create request mock object -'
u'request middleware returned a response')
elif use_toolbar:
from cms.middleware.toolbar import ToolbarMiddleware
mid = ToolbarMiddleware()
mid.process_request(request)
return request
示例7: request
def request(self, **request):
"""
Similar to parent class, but returns the request object as soon as it
has created it.
"""
environ = {
'HTTP_COOKIE': self.cookies,
'PATH_INFO': '/',
'QUERY_STRING': '',
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '',
'SERVER_NAME': 'testserver',
'SERVER_PORT': 80,
'SERVER_PROTOCOL': 'HTTP/1.1',
}
environ.update(self.defaults)
environ.update(request)
request = WSGIRequest(environ)
# Add request.user.
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
if middleware_method(request):
raise Exception("Couldn't create request mock object - "
"request middleware returned a response")
return request
示例8: request
def request(self, **request):
"""
Similar to parent class, but returns the request object as soon as it
has created it.
"""
environ = {
'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
'PATH_INFO': '/',
'QUERY_STRING': '',
'REMOTE_ADDR': '127.0.0.1',
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'SERVER_PROTOCOL': 'HTTP/1.1',
'wsgi.version': (1,0),
'wsgi.url_scheme': 'http',
'wsgi.errors': self.errors,
'wsgi.multiprocess': True,
'wsgi.multithread': False,
'wsgi.run_once': False,
}
environ.update(self.defaults)
environ.update(request)
request = WSGIRequest(environ)
# Add request.user.
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
if middleware_method(request):
raise Exception("Couldn't create request mock object - "
"request middleware returned a response")
return request
示例9: process_response
def process_response(self, request, response):
try:
if hasattr(response, 'render') and callable(response.render):
return response.render()
return response
except Exception:
import sys
from django.conf import settings
from django.core.handlers.base import BaseHandler
from django.core import signals
from django.core import urlresolvers
urlconf = settings.ROOT_URLCONF
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
receivers = signals.got_request_exception.send(
sender=self.__class__,
request=request,
)
handler = BaseHandler()
return handler.handle_uncaught_exception(
request,
resolver,
sys.exc_info(),
)
示例10: request
def request(self, **request):
handler = BaseHandler()
handler.load_middleware()
r = WSGIRequest(self._base_environ(**request))
for middleware_method in handler._request_middleware:
if middleware_method(r):
raise Exception('error on middleware {}'.format(middleware_method))
return r
示例11: request
def request(self, **request):
request = super(RequestFactory, self).request(**request)
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
if middleware_method(request):
raise Exception('request middleware returned a response')
return request
示例12: request
def request(self, **request):
request = RequestFactory.request(self, **request)
handler = BaseHandler()
handler.load_middleware()
for mw in handler._request_middleware:
if mw(request):
raise Exception('middleware returned a reponse')
return request
示例13: request
def request(self, **request):
request = RequestFactory.request(self, **request)
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
if middleware_method(request):
raise Exception("Couldn't create request mock object - "
"request middleware returned a response")
return request
示例14: request
def request(self, **request):
"Construct a generic request object."
request = RequestFactory.request(self, **request)
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware: # pylint: disable=protected-access
if middleware_method(request):
raise Exception("Couldn't create request mock object - "
"request middleware returned a response")
return request
示例15: request
def request(self, **request):
"Construct a generic request object."
request["REQUEST"] = dict()
request = RequestFactory.request(self, **request)
handler = BaseHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
if middleware_method(request):
raise Exception("Couldn't create request mock object - " "request middleware returned a response")
return request